-1

Please refer to the sample XML File

<root>
<A id="101">
<B></B>
<C id="Hello" name="World"> </C>
<D id="First D"> </D>
</A>
<X id="102"> Shawn </X>
<Y id="Java World"> </Y>
<Z> Cool </Z> 
<D id="Second D"> </D>    
</root>

I want to display Tag "D" with ID = "Second D" using Java Dom Parser functionality.

Please help me on this.

Shivam Panicker
  • 117
  • 1
  • 2
  • 9

2 Answers2

0

First of all i would decide which DOM-Parser Library you want to use. I prefer JDOM2. There are plenty of tutorial in the internet. The only thing you have to do is just to read the document (string to JDOM-Document) and then doc.getRootElement().getChildText("D"). Of course you should do some error-checkings like if the read in document is null or the root element and so on. I think this is enough for helping you to get the job done yourself.

EDIT: I saw your xml-file not well-structured as you can see with the last line where you have an closing tag but was closed in the same line above.

hasan
  • 553
  • 1
  • 5
  • 19
  • @Hasan- Thanks for the response. But doc.getRootElement().getChildText("D") returns the both values of D, i.e. First D and Second D. Since they are from different parents tree structure altogether and I need to display only "Second D", it would be great if you could share any such solution. FYI: I edited the XML as suggested. Thanks – Shivam Panicker Aug 08 '13 at 09:24
  • I think it can't do that or you described a different xml-structure. Because you have the first D as Child of A, and the second D is the child of your root... Actually it should not be possible to get the first D. But if you want to get the second, do getAttribute and check if the id is equal your wished id-value. – hasan Aug 08 '13 at 10:50
0

@Shiva. Please try the below given code and let me know the result.

XPath xPath =  XPathFactory.newInstance().newXPath();
String expression = "/root/D[@id='Second D']/text()";
NodeList nodeList1 = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
for (int i = 1; i <= nodeList1.getLength(); i++) {
System.out.println(nodeList1);
}

Suggestion: If your XML file has fewer contents then go for DOM Parser because it is easy to use with the help of XPath.

TheGaME
  • 443
  • 2
  • 8
  • 21