gpt4 book ai didi

java - 在 Java 中使用 Xpath 定位具有特定命名空间的元素

转载 作者:行者123 更新时间:2023-12-02 00:36:30 25 4
gpt4 key购买 nike

我正在尝试使用 Java 中的 Xpath 列出具有特定命名空间的元素。我有以下 xml 文件:

<pd:ProcessDefinition xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:pd="http://newsample/cred/process/2007"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<pd:name>Processes/Schemas/GetInline.process</pd:name>
<pd:startName>StartThis</pd:startName>
<pd:startType>
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="param" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</pd:startType>
<pd:endName>End</pd:endName>
<pd:endType>
<xsd:element name="End" type="xsd:string"/>
</pd:endType>
<pd:activity name="MapAnyelement">
<config>
<element>
<xsd:choice>
<xsd:element name="param" type="xsd:string"/>
<xsd:element ref="pfx:param1"/>
</xsd:choice>
</element>
</config>
<pd:coercions>
<pd:coercion xpath="root" element="pfx:param1"/>
</pd:coercions>
<pd:inputBindings/>
</pd:activity>
<pd:activity name="MapComplex">
<config>
<element>
<xsd:element name="mapComplex">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="complex1" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</element>
</config>
<pd:inputBindings>
<mapComplex>
<complex1>
<xsl:value-of select="1"/>
</complex1>
</mapComplex>
</pd:inputBindings>
</pd:activity>
<pd:activity name="MapElement">
<config>
<element>
<xsd:element name="mapElement" type="xsd:string"/>
</element>
</config>
<pd:inputBindings>
<mapElement>
<xsl:value-of select="1"/>
</mapElement>
</pd:inputBindings>
</pd:activity>
</pd:ProcessDefinition>

我使用以下代码来查找文件中的任何复杂元素是否具有具有命名空间前缀 xs 的后代,即它们属于命名空间 http://www.w3 .org/2001/XMLSchema

String expression = "/ProcessDefinition/activity|//group/activity|/ProcessDefinition/starter";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(
dDoc, XPathConstants.NODESET);
NodeListIterator iter = new NodeListIterator(nodeList);
while(iter.hasNext()) {
Node nNode = iter.next();
Element elem = (Element) nNode;
String aName = elem.getAttribute("name");
String ns = "http://www.w3.org/2001/XMLSchema";
String schemaExpr = "//*[namespace-uri() = '"+ns+"']";
NodeList nN = (NodeList) xPath.compile(schemaExpr).evaluate(nNode, XPathConstants.NODESET);
System.out.println("##### NodeList: " + nN.getLength());
}

但是,代码始终将 NodeList nN 大小返回为“0”。我在这里缺少什么?

最佳答案

在 XPath 中,非限定名称与任何 namespace 中的元素都不匹配。所以/ProcessDefinition不匹配<pd:ProcessDefinition>在您的源文档中。

最简单的解决方法是使用 XSLT 2.0+ 处理器(例如 Saxon),然后 (1) 在静态上下文中设置 defaultXPathNamespace 或 (2) 使用 /*:ProcessDefinition/*:activity 形式的步骤。

如果您想坚持使用 XPath 1.0,您可以编写 /pd:ProcessDefinition/pd:activity 形式的表达式。并设置一个识别前缀“pd”的命名空间上下文;或者您可以以 /*[local-name()='ProcessDefinition']/*[local-name()='activity']/... 的形式编写表达式

关于java - 在 Java 中使用 Xpath 定位具有特定命名空间的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com