Read a QName from an XML using Java / DOM - java

I have a QName encoded in an XML file as below. How do I read it in to a Java javax.xml.namespace.QName? Also is this a proper way to encode a QName in an XML
<messages>
<message>
<qname xmlns:msg-i="http://www.abc.com/message">msg-i:InformationMessage</qname>
</message>
</messages>
and Java code
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document messagesDoc = db.parse(file);
messagesDoc.getDocumentElement().normalize();
NodeList messages = messagesDoc.getDocumentElement().getElementsByTagName("message");
for (int i = 0; i < messages.getLength(); i++) {
//read the QName here
QName qname = ...;
}

Yes it's better way to parse the xml elements and it's tag values, use Node and Element interface to iterate between the child nodes to parse the xml element values .I hop it would help you ..

Related

How to extract XML data using Java in Android?

I have the following XML document which I'm trying to get the inner text. I have tried numerous ways, using Xpath, DOM, SAX but no success.
This is my XML, I'm not sure if it's the XML structure which is causing a problem or my code.
<?xml version="1.0"?>
<ArrayOfPurchaseEntitites xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema">
<PurchaseEntitites>
<rInstalmentAmt>634.0</rInstalmentAmt>
<rAnnualRate>12.0</rAnnualRate>
<rInterestAmt>2670.0</rInterestAmt>
<dFirstInstalment>3/31/2016 12:00:00 AM</dFirstInstalment>
<dLastInstalment>8/31/2018 12:00:00 AM</dLastInstalment>
<rInsurancePremium>1350.0</rInsurancePremium>
<sResponseCode>00</sResponseCode>
</PurchaseEntitites>
</ArrayOfPurchaseEntitites>
InputStream stream = connect.getInputStream();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(stream);
doc.normalize();
System.out.println("===============================================================");
String g = doc.getDocumentElement().getTextContent();
System.out.println(g);
NodeList rootNodes = doc.getElementsByTagName("ArrayOfPurchaseEntitites");
Node rootnode =rootNodes.item(0);
Element rootElement = (Element) rootnode;
NodeList noteslist = rootElement.getElementsByTagName("PurchaseEntitites");
for(int i = 0; i < noteslist.getLength(); i++)
{
Node theNote = noteslist.item(i);
Element noteElement =(Element) theNote;
Node theExpiryDate = noteElement.getElementsByTagName("dLastInstalment").item(0);
Element dateElement = (Element) theExpiryDate;
System.out.println(dateElement.getTextContent());
}
stream.close();
I had a similar problem where I wanted to call getElementsByTagName for the first item in a NodeList. The trick - which you already utilize - is to cast the Node to Element. However, just to be sure, I suggest you add if (rootnode instanceof Element).
Assuming you use packages javax.xml.parsers and org.w3c.dom (no wild guess) your code works nicely when the xml is read from a file.
So if there still a problem with the code (it's been a while since this question was asked) I suggest you update the question with more info regarding connect.getInputStream();.

How to create tag with namespace prefix

I am trying to add a prefix to a tag to represent a particular namespace - as can be seen below
String envelopePrefix = "omgEnv";
String businessPrefix = "omgBS";
String namespaceURI = "http://www.w3.org/2000/xmlns/";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("OmgeoMessageContainer");
rootElement.setAttributeNS(namespaceURI, "xmlns:" + envelopePrefix, "http://www.omgeo.com/schema/v1.0/envelope");
rootElement.setAttributeNS(namespaceURI, "xmlns:" + businessPrefix, "http://www.omgeo.com/schema/v1.0/BusinessServices");
doc.appendChild(rootElement);
Element messageParties = doc.createElementNS(namespaceURI, envelopePrefix + ":MessageParties");
rootElement.appendChild(messageParties);
Unfortunately my messageParties element is failing with the following error -
org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create
or change an object in a way which is incorrect with regard to
namespaces.
How are you supposed to prefix a tag with the correct namespace definition? Event the setPrefix method throws the same error.
Thanks
I do not think you can decide the prefix for a namespace element while generating XML. I did not see any such option in the JavaDocs. To create element with namespace this should be the modification.
String namespaceURI = "http://www.w3.org/2000/xmlns/";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElementNS(namespaceURI, "OmgeoMessageContainer");
doc.appendChild(rootElement);
Element messageParties = doc.createElementNS(namespaceURI, "MessageParties");
rootElement.appendChild(messageParties);
This will generate the XML with auto decided prefix for the namespaces.

Extract XML blocks as string in Java

I have an XML as below
<accountProducts>
<accountProduct>...</accountProduct>
<accountProduct>...</accountProduct>
<accountProduct>...</accountProduct>
<accountProduct>...</accountProduct>
</accountProducts>
Now I want to extract each of the accountProduct block as string. So is there any XML parsing technique to do that or I need to do string manipulation.
Any help please.
Using the DOM as suggested above, you will need to parse your XML with a DocumentBuilder.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//if your document has namespaces, you can specify that in your builder.
DocumentBuilder db = dbf.newDocumentBuilder();
Using this object, you can call the parse() method.
Your XML input can be provided to a DOM parser as a file or as a stream.
As a file...
File f = new File("MyXmlFile.xml");
Document d = db.parse(f);
As a string...
String myXmlString = "...";
InputSource ss = new InputSource(new StringReader(myXmlString));
Document d = db.parse(ss);
Once you have a Document object, you can traverse the document with DOM functions or with XPATH. This example illustrates the DOM methods.
In your example, assuming that accountProduct nodes contain only text, the following should work.
NodeList nl = d.getElementsByTagName("accountProduct");
for(int i=0; i<nl.getLength(); i++) {
Element elem = (Element)nl.item(i);
System.out.println(elem.getTextContent());
}
If accountProduct contains mixed content (text and elements), you would need more code to extract what you need.
Use JAXP for this.
The Java API for XML Processing (JAXP) is for processing XML data using applications written in the Java programming language.

Load XML into TreeMap

I have an XML config file that has just one parent and one child. This will always be like this and never change. It looks something like this:
<parent>
<child1>test</child1>
<child2>123</child2>
</parent>
I want to use java DOM (org.w3c.dom.Document) to parse the XML into a TreeMap so that I can access the attributes as keys/values. I'm guessing I'd need to create a for loop that scans through the XML and adds the key (parent) and value (child) line by line?
You can traverse the XML document using JAXP APIs, you don't need to know the structure or node names in advance
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document doc = docBuilder.parse(is);
NodeList nodeList = doc.getChildNodes();
and you can iterate on document and get the nodes and attributes
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
NamedNodeMap attributes = node.getAttributes();
//...
}

How to read comments from XML file using DOM parser

I'm trying to read the comments in an XML file. Not able to get the comment nodes after parsing it with DOM.
Code:
DocumentBuilderFactory docBldrFactry = DocumentBuilderFactory.newInstance();
docBldrFactry.setIgnoringComments(false);
DocumentBuilder docBuilder = docBldrFactry.newDocumentBuilder();
Document document = docBuilder.parse(new File("C:\\webser.xml"));
Element rootElement = document.getDocumentElement();
NodeList list = rootElement.getElementsByTagName("Bean");
Comments are under Bean element. WHen I loop through the child nodes of Bean element, I don't get the comment nodes.
Here is the XML
<Beans>
<Bean>
<!-- Testing Comments -->
<API name ="xyz" />
</Bean>
</Beans>
Hope this helps :)
XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream("file.xml"));
while (xr.hasNext()) {
if (xr.next() == XMLStreamConstants.COMMENT) {
String comment = xr.getText();
} }

Categories