Is there any way to take an unknown schema xml file and convert the values, tags, etc from the xml file into pojo? I looked at jaxb and it seems like the best way to use that is if you already know the xml schema. So basically, I want to be able to parse the tags from the xml put each into its own object maybe through the use of an arraylist. Did I just not fully understand what jaxb can or is there a better tool that can do this, or is it just too hard to implement?
In the hope that this helps you to understand your situation!
public static void dumpAllNodes( String path ) throws Exception {
DocumentBuilder parser =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = parser.parse(new File(path));
NodeList nodes = doc.getElementsByTagNameNS( "*", "*" );
for( int i = 0; i < nodes.getLength(); i++ ){
Node node = nodes.item( i );
System.out.println( node.getNodeType() + " " + node.getNodeName() );
}
}
The NodeList nodes contains all element nodes, in document order (opening tag). Thus, elements contained within elements will be in that list, all alike. To obtain the attributes of a node, call
NamedNodeMap map = node.getAttributes();
The text content of a node is available by
String text = node.getTextContent();
but be aware that calling this returns the text in all elements of a subtree.
OTOH, you may call
Element root = doc.getDocumentElement();
to obtain the root element and then descend the tree recursively by calling Element.getChildNodes() and process the nodes (Element, Attr, Text,...) one by one. Also, note that Node.getParentNode() returns the parent node, so you could construct the XPath for each node even from the flat list by repeating this call to the root.
It simply depends what you expect from the resulting data structure (what you call ArrayList). If, for instance, you create a generic element type (MyElement) containing one map for attributes and another one for child elements, the second map would have to be
Map<String,List<MyElement>> name2elements
to provide for repeated elements - which makes access to elements occurring only once a little awkward.
I hope that I have illustrated the problems of generic XML parsing, which is not a task where JAXB can help you.
Related
Application Background:
Basically, I am building an application in which I am parsing the XML document using SAX PARSER for every incoming tag I would like to know its datatype and other information so I am using the XSD associated with that XML file to get the datatype and other information related to those tags. Hence, I am parsing the XSD file and storing all the information in Hashmap so that whenever the tag comes I can pass that XML TAG as key to my Hashmap and obtain the value (information associated with it which is obtained during XSD parsing) associated with it.
Problem I am facing:
As of now, I am able to parse my XSD using the DocumentBuilderFactory. But during the collection of elements, I am able to get only one type of element and store it in my NODELIST such as elements with tag name "xs:element". My XSD also has some other element type such as "xs:complexType", xs:any etc. I would like to read all of them and store them into a single NODELIST which I can later loop and push to HASHMAP. However I am unable to add any additional elements to my NODELIST after adding one type to it:
Below code will add tags with the xs:element
NodeList list = doc.getElementsByTagName("xs:element");
How can I add the tags with xs:complexType and xs:any to the same NODELIST?
Is this a good way to find the datatype and other attributes of the XSD or any other better approach available. As I may need to hit the HASHMAP many times for every TAG in XML will there be a performance issue?
Is DocumentBuilderFactory is a good approach to parse XML or are there any better libaraies for XSD parsing? I looked into Xerces2 but could not find any good example and I got struck and posted the question here.
Following is my code for parsing the XSD using DocumentBuilderFactory:
public class DOMParser {
private static Map<String, Element> xmlTags = new HashMap<String, Element>();
public static void main(String[] args) throws URISyntaxException, SAXException, IOException, ParserConfigurationException {
String xsdPath1 = Paths.get(Xerces2Parser.class.getClassLoader().getResource("test.xsd").toURI()).toFile().getAbsolutePath();
String filePath1 = Path.of(xsdPath1).toString();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(filePath1));
NodeList list = doc.getElementsByTagName("xs:element");
System.out.println(list.getLength());
// How to add the xs:complexType to same list as above
// list.add(doc.getElementsByTagName("xs:complexType"));
// list = doc.getElementsByTagName("xs:complexType");
// Loop and add data to Map for future lookups
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element) list.item(i);
if (element.hasAttributes()) {
xmlTags.put(element.getAttribute("name"), element);
}
}
}
}
I don't know what you are trying to achieve (you have described the code you are writing, not the problem it is designed to solve) but what you are doing seems misguided. Trying to get useful information out of an XSD schema by parsing it at the XML level is really hard work, and it's clear from the questions you are asking that you haven't appreciated the complexities of what you are attempting.
It's hard to advise you on the low-level detail of maintaining hash maps and node lists when we don't understand what you are trying to achieve. What information are you trying to extract from the schema, and why?
There are a number of ways of getting information out of a schema at a higher level. Xerces has a Java API for accessing a compiled schema. Saxon has an XML representation of compiled schemas called SCM (the difference from raw XSD is that all the work of expanding xs:include and xs:import, expanding attribute groups, model groups, and substitution groups etc has been done for you). Saxon also has an XPath API (a set of extension functions) for accessing compiled schema information.
I am writing a Java program that will create an XML file from various pieces of data.
There are attribute strings containing URLs that are reused throughout the XML. I wanted to reuse these attributes (i.e., copy them from one element to another). I currently have something like this:
public class copyAttributes {
public static final String google_url = "http://www.google.com";
DocumentBuilderFactor docFac = DocumentBuilderFactory.newInstance();
DocumentBuilder build = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
public static Attr googleAttr = doc.createAttribute("ref:GoogleMainSite");
googleAttr.setValue(google_url);
Element rootElement = doc.createElement("Root_Element");
rootElement.setAttributeNode(googleAttr);
...this is fine so far if I don't have any other elements.
Now, I want to have multiple elements containing that same Google URL attribute node. I know that's redundant, but I'm following an XSD that specifically says attributes have to be reused. I know you can't just do this:
Element childElement = doc.createElement("Child_Element");
childElement.setAttributeNode(googleAttr);
rootElement.appendChild(childElement);
...because I know you will get an INUSE_ATTRIBUTE_ERR (I tried, that's how I know). But I want to reuse this attribute, as it will occur many times throughout the XML.
I did find this: sample code for copying attributes from one element to another, but when I included that sample "Utils" class in my package and called it this way:
Utils utils = new Utils();
utils.copyAttributes(rootElement, childElement);
...I receive a "NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces."
There isn't much information out there about this "Namespace_err" message.
The other solution I found is to simply clone an element. But this doesn't solve my problem either, since in some cases I won't want to reuse all of the attributes of another element, I will only want to use a couple of them.
Basically my question is: How do you go about reusing attribute nodes on multiple elements in an XML schema created via a Java program?
you can try this:
public void copyAttributes(Element from, Element to)
{
NamedNodeMap attributes = from.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Attr node = (Attr) attributes.item(i);
to.setAttributeNode((Attr) node.cloneNode(false));
}
}
My XML file looks like this:
<Messages>
<Contact Name="Robin" Number="8775454554">
<Message Date="24 Jan 2012" Time="04:04">this is report1</Message>
</Contact>
<Contact Name="Tobin" Number="546456456">
<Message Date="24 Jan 2012" Time="04:04">this is report2</Message>
</Contact>
<Messages>
I need to check whether the 'Number' attribute of Contact element is equal to 'somenumber' and if it is, I'm required to insert one more Message element inside Contact element.
How can it be achieved using DOM? And what are the drawbacks of using DOM?
The main drawback to using a DOM is it's necessary to load the whole model into memory at once, rather than if your simply parsing the document, you can limit the data you keep in memory at one point. This of course isn't really an issue until your processing very large XML documents.
As for the processing side of things, something like the following should work:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(is);
NodeList contacts = dom.getElementsByTagName("Contact");
for(int i = 0; i < contacts.getLength(); i++) {
Element contact = (Element) contacts.item(i);
String contactNumber = contact.getAttribute("Number");
if(contactNumber.equals(somenumber)) {
Element newMessage = dom.createElement("Message");
// Configure the message element
contact.appendChild(newMessage);
}
}
DOM has two main disadvantages:
It requires reading of the complete XML into a Java representation in memory. That can be both time and memory consuming
It is a pretty verbose API, so you need to write a lot of code to achieve simple things like you're asking for.
If time and memory consumption is OK for you, but verbosity is not, you could still use jOOX, a library that I have created to wrap standard Java DOM objects to simplify manipulation of XML. These are some examples of how you would implement your requirement with jOOX:
// With css-style selectors
String result1 = $(file).find("Contact[Number=somenumber]").append(
$("<Message Date=\"25 Jan 2012\" Time=\"23:44\">this is report2</Message>")
).toString();
// With XPath
String result2 = $(file).find("//Contact[#Number = somenumber]").append(
$("<Message Date=\"25 Jan 2012\" Time=\"23:44\">this is report2</Message>")
).toString();
// Instead of file, you can also provide your source XML in various other forms
Note that jOOX only wraps standard Java DOM. The underlying operations (find() and append(), as well as $() actually perform various DOM operations).
You will do something to this effect.
Get the NodeList of Contact element.
Iterate through the NodeList and get Contact element.
Get Number through contact.getAttribute("Number") where contact is of type Element.
If your number equals someNumber, then add Message by calling contact.appendChild(). Message must be an element.
Use the Element class to create a new element
Element message = doc.createElement("Message");
message.setAttribute("message", strMessage);
Now add this element after whatever element you want using
elem.getParentNode().insertBefore(message, elem.getNextSibling());
You might want to take a look at this tutorial its about exactly what you want to do
I'm trying to read/copy a certain part of a xml document in JAVA and then save this part as a new xml document. So like in de example below you see studentinfo and contact info, I just want to select studentinfo and copy the entire area so nodes and elements.
I can only find info about selecting only the element or only the nodes.
So help would be appreciated, thank you.
<header>
<body>
<studentinfo>
<name>Student Name<name>
<studentid>0987654321<studentid>
<Location>USA<Location>
<studentinfo>
<contactinfo>
<email>email#email.com<email>
<address>somewhere 1<address>
<postalcode>123456<postalcode>
<contactinfo>
<body>
<header>
I'm going to make a big assumption, and that is that you are using the org.w3c.dom.Document api.
This is a two step process:
Document doc = parse(xmlSource);
Document targetDoc = openTargetDoc();
Node copyTo = findWhereYouWantToCopyStuffTo(targetDoc);
// Find the node or nodes to want to copy.. could use XPath or some other search
NodeList studentinfoList = doc.getElementsByTagName("studentinfo");
// for each found... make a copy (via importNode) and attach to some point in the target doc
for( int i = 0; i < studnetinfoList.getLength(); i ++ ){
Node n = studentinfoList.item(i);
Node copyOfn = targetDoc.importNode(n,true);
copyTo.appendChild(copyOfn);
}
If this isn't what you are looking for, you might need to add a bit more detail of what you wish to copy and where to, using what api etc.
I have an XML file where some sub tags (child node elements) are optional.
e.g.
<part>
<note>
</rest>
</note>
<note>
<pitch></pitch>
</note>
<note>
<pitch></pitch>
</note>
</part>
But when I read the XML files by tags, it throws a NullPointerException - since some sub-tags are optional (e.g. rest and pitch in above example). How can I filter this out? I couldn't come across any methods to find whether an element exists by a particular tag name. Even if I have a condition to check whether getElementsByTagName("tag-name") method not returns NULL - still it goes in the condition body and obviously throw the exception.
How may I resolve this?
The java code is:
if(fstelm_Note.getElementsByTagName("rest")!=null){
if(fstelm_Note.getElementsByTagName("rest")==null){
break;
}
NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
Element restElm = (Element)restElmLst.item(0);
NodeList rest = restElm.getChildNodes();
String restVal = ((Node)rest.item(0)).getNodeValue().toString();
}else if(fstelm_Note.getElementsByTagName("note")!=null){
if(fstelm_Note.getElementsByTagName("note")==null){
break;
}
NodeList noteElmLst = fstelm_Note.getElementsByTagName("note");
Element noteElm = (Element)noteElmLst.item(0);
NodeList note = noteElm.getChildNodes();
String noteVal = ((Node)note.item(0)).getNodeValue().toString();
}
Any insight or suggestions are appreciated.
Thanks in advance.
I had this very same problem (using getElementsByTagName() to get "optional" nodes in an XML file), so I can tell by experience how to solve it. It turns out that getElementsByTagName does not return null when no matching nodes are found; instead, it returns a NodeList object of zero length.
As you may guess, the right way to check if a node exists in an XML file before trying to fetch its contents would be something similar to:
NodeList nl = element.getElementsByTagName("myTag");
if (nl.getLength() > 0) {
value = nl.item(0).getTextContent();
}
Make sure to specify a "default" value in case the tag is never found.
It may be that your NodeLists are not null, but are empty. Can you try changing your code like this and see what happens?
NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
if (restElmLst != null && !restElmLst.isEmpty())
{
Element restElm = (Element)rests.item(0);
...
etc. (Doublecheck syntax etc., since I'm not in front of a compiler.)
Your requirements are extremely unclear but I would very likely use the javax.xml.xpath package to parse your XML document with the XML Path Language (XPath).
Have a look at:
XML Validation and XPath Evaluation in J2SE 5.0
Parsing an XML Document with XPath
But you should try to explain the general problem you are trying to solve rather than the specific problem you're facing. But doing so, 1. you will probably get better answers and 2. the current chosen path might not be the best one.
Try something like below
bool hasCity = OrderXml.Elements("City").Any();
where OrderXml is parent element.
First you need to create the nodelist and then check the length of nodelist to check whether the current element exists or not in the xml string.
NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
if (restElmLst.getLength() > 0) {
String restVal = restElm.getElementsByTagName("rest").item(0).getTextContent();
}