【问题标题】:Extract specific redundant tag from xml in java从java中的xml中提取特定的冗余标签
【发布时间】:2023-03-10 01:53:01
【问题描述】:

我想从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 代码来做到这一点?

【问题讨论】:

标签: java xml xslt


【解决方案1】:

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

基于...

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

看看:

更多详情

【讨论】:

  • 你知道如何使用字符串表达式提取方法解析文件吗,因为我遇到了“Unicode:0x2”的问题,只能通过逐行读取文件并提取 内容;有什么帮助吗?
  • 您可以通过InputSource 传递Reader 并允许DocumentBuilder 解析内容。
  • 请您提供代码示例好吗?
  • db.parse(new InputSource(new BufferedReader(new FileReader(...))); 或类似的...
  • 即使使用此代码,我也收到相同的“致命错误”:发现无效的 XML 字符 (Unicode: 0x2)
猜你喜欢
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多