【问题标题】:Locating XML element anywhere in the document with Java使用 Java 在文档中的任何位置定位 XML 元素
【发布时间】:2016-01-28 20:25:36
【问题描述】:

给定以下 XML(示例):

<?xml version="1.0" encoding="UTF-8"?>
<rsb:VersionInfo xmlns:atom="http://www.w3.org/2005/Atom" xmlns:rsb="http://ws.rsb.de/v2">
    <rsb:Variant>Windows</rsb:Variant>
    <rsb:Version>10</rsb:Version>
</rsb:VersionInfo>

我需要获取VariantVersion 的值。我目前的方法是使用 XPath,因为我不能依赖给定的结构。我只知道文档中某处有一个元素rsb:Version

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//Variant";
InputSource inputSource = new InputSource("test.xml");
String result = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
System.out.println(result);

然而这并没有输出任何东西。我尝试了以下 XPath 表达式:

  • //变体
  • //变体/text()
  • //rsb:变体
  • //rsb:Variant/text()

什么是正确的 XPath 表达式?或者有没有更简单的方法来获取这个元素?

【问题讨论】:

  • XPathFactory 需要使用 NamespaceContext 创建。一旦你弄清楚了,•//rsb:Variant XPath 应该可以工作了。
  • 也请看这个问题。 stackoverflow.com/questions/2811001/…
  • @JerryM 的评论确实解决了我的问题。

标签: java xml xpath


【解决方案1】:

我建议只遍历文档以找到给定的标签

public static void main(String[] args) throws SAXException, IOException,ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("test.xml"));

    NodeList nodeList = document.getElementsByTagName("rsb:VersionInfo");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

编辑:Yassin 指出它不会获得子节点。这应该会为您指明获取孩子的正确方向。

private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

【讨论】:

  • 不应该是 rsb:VersionInfo 吗?
  • 谢谢,@michael-quatrani。您的回答非常有帮助,我已经为其他方法实现了您的机制。但是,我选择了另一条评论作为我的首选答案。
  • @Robert 没问题!很高兴你把它整理好了。
猜你喜欢
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
  • 2011-05-13
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
相关资源
最近更新 更多