1

I have an xml trying to parse & read it, but dont know how many nodes the xml may contain? So I am trying to read the node & node values ?

How I get the same say:

<company>
    <personNam>John</personName>
    <emailId>abc@test.com</emaiId>
    <department>Products</department>
    (may have additionaly nodes & values for same)
</company>

Sorry forgot to add my code, using Dom:-

Document document = getDocumentBuilder().parse(new ByteArrayInputStream(myXML.getBytes("UTF-8")));          
String xPathExp = "//company";
XPath xPath = getXPath();
NodeList nodeList = (NodeList)xPath.evaluate(xPathExp, document, XPathConstants.NODESET);           
nodeListSize = nodeList.getLength();
System.out.println("#####nodeListSize"+nodeListSize);

for(int i=0;i<nodeListSize;i++){
    element=(Element)nodeList.item(i);
    m1XMLOutputResponse=element.getTextContent();
    System.out.println("#####"+element.getTagName()+"   "+element.getTextContent());
}
moritz
  • 5,094
  • 1
  • 26
  • 33
Vardhaman
  • 899
  • 3
  • 11
  • 10

2 Answers2

1

Consider using the JAXB library. It's really a painless way of mapping your XML to Java classes and back. The basic principle is that JAXB takes your XML Schemas (XSD) and generates corresponding Java classes for you. Then you just call marshall or unmarshall methods which populate your Java class with the contents of the XML, or generates the XML from your Java class.

The only drawback is, of course, that you'd need to know how to write the XML Schemas :)

janhink
  • 4,943
  • 3
  • 29
  • 37
0

Learn how to use XML DOM. Here is an example on how to use XML DOM to fetch node and node values.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207