<?xml version="1.0" ?>
<input>
<sys>
<protocol>TL1</protocol>
<ipAddress>10.05.2.3</ipAddress>
<port>2001</port>
<prompt>agent</prompt>
<TL1Command>
<type>get</type>
<command_code>...........</command_code>
<staging_block>
<tid>...........</tid>
<aid>...........</aid>
<ctag>..........</ctag>
<gen_block>.....</gen_block>
</staging_block>
<payload_block>
<data_block>.......</data_block>
</payload_block>
</TL1Command>
</sys>
<sys>
<protocol>TL1</protocol>
<ipAddress>10.5.2.98</ipAddress>
<port>2001</port>
<prompt>agent</prompt>
<TL1Command>
<type>get</type>
<command_code>...........</command_code>
<staging_block>
<tid>...........</tid>
<aid>...........</aid>
<ctag>..........</ctag>
<gen_block>.....</gen_block>
</staging_block>
<payload_block>
<data_block>.......</data_block>
<data_block>.......</data_block>
<data_block>.......</data_block>
</payload_block>
</TL1Command>
</sys>
</input>
I want to know how to parse this XML using Java. Such that I can use that data as it is in the same given way for my program. I know of how to parse it but the problem is for each command there might be different number of data blocks. So after parsing I need to use respective datablocks for respective commands. I mean for first command while retriving I should get only one data block value and for 2nd command 3 data blocks and so on. Please let me know any sample code for solving this issue.
There are two basic approaches to parsing XML.
Pick whichever is most appropriate for your circumstances.
Simplest way would be to load the document as a DOM Document
Then get what you need using XPath
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
NodeList nodeList = XPathAPI.selectNodeList(document, "/sys");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println(node.getTextContent());
}
Check out an xpath tutorial here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With