Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need Help - XML Parsing - JDOM

 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am using jdom. i tried getText, getChildText etc. Nothing worked. Please help.

<xinfolist>
<xinfo name="A">a</xinfo>
<xinfo name="B">b</xinfo>
<xinfo name="C">c</xinfo>
<xinfo name="D">d</xinfo>
</xinfolist>


how can i extract the content of <xinfolist>? so that i can print as shown below.

<xinfo name="A">a</xinfo>
<xinfo name="B">b</xinfo>
<xinfo name="C">c</xinfo>
<xinfo name="D">d</xinfo>

thanks,

 
Vinod Borole
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suggest go for XPath
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I doubt that you can get that list of elements in one block of text (unless they're in a CDATA section, but I'm assuming they're not).

XML APIs are meant for working with XML elements, tags and attributes - if you want to get a string that's made up of several tags, then you'll need to assemble that yourself by traversing through the xinfolist child elements.
 
Sanjay Virkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your Jdom library has a class XMLOutputter.

1) Define a variable of type XMLOutputtter

XMLOutputter strOutputter = new XMLOutputter();

2) Define a string variable.

String l_strXmlForElement;

3) Once you read your element using jdom, (which may or may not have childrens i.e. complex or simple type)
use xmloutputter's outputString method to capture xml for that element in String variable

l_strXmlForElement = strOutputter_.outputString(l_cElem);

This string will contain entire XML element in it. You can print this string.

One suggestion.
Working in Jdom is simple but if your xsd changes frequently or if it is complex, You have to write too much of code to read each element, validate it,
fetch sub elements, traverse list of childrens etc. So consider using xml<>java binding like Castor or Jaxb.

With it you follow simple steps.

1) Defiine schema (.xsd) for for xml
2) Generate code for the schema using readymade code generators.
3) Use classes created in step 2 to marshal, unmarshal, validate, print xml content.


Hope this helps





 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic