java - 获取 XML 标签的 XPath

标签 java xml xslt xpath

如果我有如下所示的 XML 文档:

<foo>
   <foo1>Foo Test 1</foo1>
   <foo2>
       <another1>
           <test10>This is a duplicate</test10>
       </another1>
   </foo2>
   <foo2>
       <another1>
           <test1>Foo Test 2</test1>
       </another1>
   </foo2>
   <foo3>Foo Test 3</foo3>
   <foo4>Foo Test 4</foo4>
</foo>

如何获取 <test1> 的 XPath例如?因此输出应该类似于:foo/foo2[2]/another1/test1

我猜代码看起来像这样:

public String getXPath(Document document, String xmlTag) {
   String xpath = "";
   ...
   //Get the node from xmlTag
   //Get the xpath using the node
   return xpath;
}

比方说String XPathVar = getXPath(document, "<test1>"); 。我需要返回一个可以在以下代码中使用的绝对 xpath:

XPath xpath = XPathFactory.newInstance().newXPath(); 
XPathExpression xpr = xpath.compile(XPathVar); 
xpr.evaluate(Document, XPathConstants.STRING); 

但它不能是像 //test1 这样的快捷方式因为它也将用于元数据目的。

通过以下方式打印结果时:

System.out.println(xpr.evaluate(Document, XPathConstants.STRING));

我应该获取节点的值。所以如果 XPathVar = foo/foo2[2]/another1/test1然后我应该回来:

Foo Test 2而不是This is a duplicate

最佳答案

您“获取”xpath 的方式与“获取”sql 的方式不同。

xpath 是您根据对 xml 文档或架构的理解编写的查询,就像 sql 是您根据对数据库架构的理解编写的查询一样 - 您无法“获取”其中任何一个。

我可以简单地通过从给定节点回溯节点来从 DOM 生成 xpath 语句,尽管一般来说,考虑到每个节点上的属性值,这样做会使生成的代码几乎无用。例如(它附带一个警告,表明这将找到具有给定名称的第一个节点,xpath 远不止于此,您也可以只使用 xpath //foo2):

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class XPathExample 
{
  private static String getXPath(Node root, String elementName)
  {
    for (int i = 0; i < root.getChildNodes().getLength(); i++)
    {
      Node node = root.getChildNodes().item(i);

      if (node instanceof Element)
      {
        if (node.getNodeName().equals(elementName))
        {
          return "/" + node.getNodeName();
        }
        else if (node.getChildNodes().getLength() > 0)
        {
          String xpath = getXPath(node, elementName);
          if (xpath != null)
          {
            return "/" + node.getNodeName() + xpath;
          }
        }
      }
    }

    return null;
  }

  private static String getXPath(Document document, String elementName)
  {
    return document.getDocumentElement().getNodeName() + getXPath(document.getDocumentElement(), elementName);
  }

  public static void main(String[] args) 
  {
    try 
    {
      Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
        new ByteArrayInputStream(
          ("<foo><foo1>Foo Test 1</foo1><foo2><another1><test1>Foo Test 2</test1></another1></foo2><foo3>Foo Test 3</foo3><foo4>Foo Test 4</foo4></foo>").getBytes()
        )
      );

      String xpath = "/" + getXPath(document, "test1");
      System.out.println(xpath);        

      Node node1 = (Node)XPathFactory.newInstance().newXPath().compile(xpath).evaluate(document, XPathConstants.NODE);
      Node node2 = (Node)XPathFactory.newInstance().newXPath().compile("//test1").evaluate(document, XPathConstants.NODE);

      //This evaluates to true, hence you may as well just use the xpath //test1.
      System.out.println(node1.equals(node2));
    }
    catch (Exception e) 
    {
      e.printStackTrace();
    }
  }
}

同样,您可以编写一个 XML 转换,将 xml 文档转换为一系列 xpath 语句,但这种转换会比首先编写 xpath 更复杂,而且基本上毫无意义。

关于java - 获取 XML 标签的 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14435767/

相关文章:

具有默认命名空间设置为 xmlns 的 XML 源的 XSLT

C# 使用日历参数调用 Java Web 服务

java - O(N!*N) 是一个可接受的大复杂度类,还是我删除常量并只说 O(N!) ?

java - com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure Software caused connection abort: recv failed

c# - 使用 XElement 在 C# 中获取最后一个元素

xml - Soap xml 响应使用 xsd 文件进行验证

XSLT:如何检查多个节点是否适用于所有节点的某个值

Java如何限制一行打印的字符数

xml - fo :external-graphic src ="data:image/png;base64, ..." as attribute

xml - XSLT - 递归模板