Java根据org.w3c.dom.Node计算XPath



我现在正在学习一点Java,有一个关于XPath的问题。

我有一个很大的Xml,我希望使用XPath能够抓取一个特定的节点,然后对这个小块Xml发起进一步的XPath调用。

这是我的Xml的大致轮廓:

<Page>
  <ComponentPresentations>
    <ComponentPresentation>
      <Component>
        <Title>
      <ComponentTemplate> 
    <ComponentPresentation>
      <Component>
        <Title>
      <ComponentTemplate> 

我的第一个XPath根据<ComponenTemplate> Id值的值选择<Component>节点:

String componentExpFormat = "/Page/ComponentPresentations/ComponentPresentation/ComponentTemplate/Id[text()='%1$s']/ancestor::ComponentPresentation";
String componentExp = String.format(componentExpFormat, template);
XPathExpression expComponent = xPath.compile(componentExp);
Node componentXml = (Node) expComponent.evaluate(xmldoc, XPathConstants.NODE);

这给了我想要的<Component>,但我似乎无法对节点使用XPath:

String componentExpTitle = "/Component/Fields/item/value/Field/Name[text()='title']/parent::node()/Values/string";                                  
XPathExpression expTitle = xPath.compile(componentExpTitle);
String eventName = expTitle.evaluate(componentXml, XPathConstants.STRING).toString();

如果没有这个,我每次都必须包含完整的XPath:

/Page/ComponentPresentations/ComponentPresentation/ComponentTemplate/Id[text()='%1$s']/ancestor::ComponentPresentation/Component/Fields/item/value/Field/Name[text()='title']/parent::node()/Values/string

这是唯一的方法吗?

欢呼

带前导斜杠的XPath表达式

/Component/Fields/item

是绝对的,当您使用特定上下文节点对其求值时,它将从上下文节点所属的文档的根开始查找。如果你去掉前面的斜杠

Component/Fields/item

它将查找上下文节点的Component子节点。

作为题外话,您可以简化这些xpath,您不需要使用ancestor::的所有上下树的东西,您也不需要使用text():
componentExpFormat = "/Page/ComponentPresentations/ComponentPresentation[ComponentTemplate/Id='%1$s']";
componentExpTitle = "Component/Fields/item/value/Field[Name='title']/Values/string";

最新更新