【问题标题】:Document - How to get a tag's value by its name?文档 - 如何通过名称获取标签的值?
【发布时间】:2011-11-21 09:42:44
【问题描述】:

我正在使用 Java 的 DOM 解析器来解析 XML 文件。

假设我有以下 XML

<?xml version="1.0"?>

<config>
    <dotcms>
        <endPoint>ip</endPoint>
    </dotcms>
</config>

</xml>

我喜欢获取 'endPoint' 的值。我可以使用以下代码 sn-p 来完成。 (假设我已经用 DocumentBuilder 解析过了)

NodeList nodeList = this.doc.getElementByTagName("dotcms");
Node nValue = (Node) nodeList.item(0);
return nValue.getNodeValue();

是否可以通过字段名称获取字段的值?喜欢……

Node nValue = nodeList.getByName("endPoint") 类似这样的...?

【问题讨论】:

    标签: java xml dom


    【解决方案1】:

    您应该使用XPath 来处理这些类型的任务:

    //endPoint/text()
    

    或:

    /config/dotcms/endPoint/text()
    

    当然,Java 有一个用于 XPath 的内置 support

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//endPoint/text()");
    Object value = expr.evaluate(doc, XPathConstants.STRING);
    

    【讨论】:

    • // 太棒了!!我很感激!简短但有用的答案。
    【解决方案2】:

    您还可以使用jOOX,一个类似于jquery 的 DOM 包装器,以编写更少的代码:

    // Using css-style selectors
    String text1 = $(document).find("endPoint").text();
    
    // Using XPath
    String text2 = $(document).xpath("//endPoint").text();
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      相关资源
      最近更新 更多