-1

I would like to extract the content of "body" from xml file

<row>
<field name="id">28479</field>
<field name="commit_id">53162</field>
<field name="user_id">16</field>
<field name="body">test test test</field>
<field name="line" xsi:nil="true" />
<field name="position" xsi:nil="true" />
<field name="comment_id">390328</field>
<field name="ext_ref_id">524dd257bd3543ae270027f6</field>
<field name="created_at">2011-05-19 01:37:02</field>
</row>
<row>
 ....
</row>
  ...

The output that I'm looking for is

 test test test

how could I do that by using java code?

1 Answers1

0

You should consider using the XPath API which will allow you to query the XML content, for example...

Based on...

<?xml version="1.0" encoding="UTF-8"?>
<row>
    <field name="id">28479</field>
    <field name="commit_id">53162</field>
    <field name="user_id">16</field>
    <field name="body">test test test</field>
    <field name="line" xsi:nil="true" />
    <field name="position" xsi:nil="true" />
    <field name="comment_id">390328</field>
    <field name="ext_ref_id">524dd257bd3543ae270027f6</field>
    <field name="created_at">2011-05-19 01:37:02</field>
</row>

And using...

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse(new File("Test.xml"));
    XPath xpath = XPathFactory.newInstance().newXPath();

    // Find the "thing" node...
    XPathExpression thingExpr = xpath.compile("/row/field[@name='body']");
    Node body = (Node) thingExpr.evaluate(dom, XPathConstants.NODE);
    if (body != null) {
        System.out.println(body.getTextContent());
    }

} catch (Exception exp) {
    exp.printStackTrace();
}

Outputs

test test test

Take a look at:

For more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366