Load XML into TreeMap - java

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();
//...
}

Related

Import Tag from xml file to another using JAVA

I do my work with this piece and my problem is simple. Just changing the place of transfer. I did not know what is the matter responsible for determining the place of transportation in the first or last content.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document doc = null;
Document doc2 = null;
String a = "E:\\1.xml" ;
String c ;
try {
db = dbf.newDocumentBuilder();
doc = db.parse(new File(a));
doc2 = db.parse(new File("E:\\L (1).xml"));
NodeList ndListFirstFile = doc.getElementsByTagName("med");
Node nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(0), true);
NodeList nList2 = doc2.getElementsByTagName("end");
for (int i = f; i <g; i++) {
c = +i+"" ;
doc2 = db.parse(new File("E:\\L ("+c+").xml"));
for (int temp = 0; temp < nList2.getLength(); temp++) {
nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(temp), true);
ndListFirstFile.item(0).appendChild(nodeArea);
}
}
This is done from two files, and it works well, but the place of transferring the tag is at the end of the content. I want it at the beginning of the content
<med>
I move the Tag "dat" and it is moved at the end of the Tag "med" content
<dat>We have come to the wrong place, my friend</dat></med>
<med><dat>We want to get better here</dat>
I want to move Tag dat
To be the first content from Tag med
</med>
That's it
From the appendChild docs:
Adds the node newChild to the end of the list of children of this node.
So it is adding it to the end as expected.
To insert it before any other element on that node, you can try:
ndListFirstFile.item(0).insertBefore(nodeArea, ndListFirstFile.item(0).getFirstChild());

How to get XML node names without namespace in java?

I have an xml file having data which looks like given below:
....
<ems:MessageInformation>
<ecs:MessageID>2147321820</ecs:MessageID>
<ecs:MessageTimeStamp>2016-01-01T04:38:33</ecs:MessageTimeStamp>
<ecs:SendingSystem>LD</ecs:SendingSystem>
<ecs:ReceivingSystem>CH</ecs:ReceivingSystem>
<ecs:ServicingFipsCountyCode>037</ecs:ServicingFipsCountyCode>
<ecs:Environment>UGS-D8UACS02</ecs:Environment>
</ems:MessageInformation>
....
There are many other nodes also. All nodes have namespace like ecs,tns,ems etc. I am suing following code part to extract all node names without namespace.
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
//System.out.println(node.getNodeName());
System.out.println(node.getLocalName());
}
}
But when I execute this code, it's printing null for individual node. Can someone tell me what I am doing wrong here?
I read on internet and I came to know that node.getLocalName() will give node name without namespace. What is wrong then in my case?
You need to set the document builder factory to be namespace aware first. Then getLocalName() will start returning non-null values.
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setNamespaceAware(true); // <=== here
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));

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 get containing Node Name from xml namespace

I've got XPath of XML with it's structure like
<Statement xsi:type="conditionStatement">
<Id>CONDITION_0001</Id>
<Bounds>
<xValue>13</xValue>
<yValue>145</yValue>
<Height>402</Height>
<Width>513</Width>
</Bounds>
.........
.........
</statement>
Xpath takes me to xsi:type. But when I'm trying to get the name of node which is "statement" as expected, it's getting null.
My code for this is:-
nodeList = (NodeList) xPath.compile(xPathSrcFile).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
nodeList.item(i).getParentNode();
}
For rest of the cases, code is working perfectly fine but when it gets to "xsi", code is throwing nullpointer exception.
Need some help to get node name from this.
try this
NodeList nodeList = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream inputStream= new FileInputStream(file);//xmlDocument as file
Reader reader = new InputStreamReader(inputStream,"ISO-8859-1");
InputSource is = new InputSource(reader);
is.setEncoding("ISO-8859-1");
Document doc = db.parse(is);
Element docEle = doc.getDocumentElement();
nodeList = docEle.getElementsByTagName("Statement");
1 Your XML file is incorrect:
it begins with Statement
and ends with /statement
2 you need this at root tag:
< root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
3 to get the name of you tag, use:
nodeList.item(i).getTagName();
4 what is your Xpath ?

Read a QName from an XML using Java / DOM

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 ..

Categories