从java中的xml中提取特定的冗余标记

时间:2014-06-25 05:43:10

标签: java xml xslt

我想从xml文件中提取“body”的内容

<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>
  ...

我正在寻找的输出是

 test test test

我怎么能用java代码呢?

1 个答案:

答案 0 :(得分:0)

您应该考虑使用XPath API,它允许您查询XML内容,例如......

基于......

<?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>

使用......

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();
}

输出

test test test

看看:

了解更多详情