xml - Xpath 1.0 表达式获取任何请求的值

标签 xml xpath

我不确定这是否可能?但我想知道我们是否可以使用通用 Xpath 表达式来获取任何请求的 documentIdentifer 值。

请求

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:cidx:names:specification:ces:schema:all:5:0">
   <soapenv:Header/>
   <soapenv:Body>
      <Invoice Version="3.0">
         <Header>
            <ThisDocumentIdentifier>
               <DocumentIdentifier>0000001193567128</DocumentIdentifier>
            </ThisDocumentIdentifier>
            <ThisDocumentDateTime>
               <DateTime DateTimeQualifier="On">20150520T145204Z</DateTime>
            </ThisDocumentDateTime>
            </Header>
      </Invoice>
   </soapenv:Body>
</soapenv:Envelope>

**Xpath **
/*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='Invoice']/*[local-name()='Header']/*[local-name()='ThisDocumentIdentifier']/*[local-name()='DocumentIdentifier']

我能够得到这个值。

我的问题是根元素不断变化,但格式保持不变。我只需要<DocumentIdentifier>0000001193567128</DocumentIdentifier> .

就像根元素是 <OrderCreate>而不是使用
这个 Xpath
/*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='OrderCreate']/*[local-name()='Header']/*[local-name()='ThisDocumentIdentifier']/*[local-name()='DocumentIdentifier']

有没有其他实现值(value)的方法?

最佳答案

All I need to get of <DocumentIdentifier>0000001193567128</DocumentIdentifier>



那将是 //DocumentIdentifier , 干净利落。

您不需要在 XPath 中过于具体。

由于您使用 XSLT,请声明输入文档中出现的 namespace 并避免 local-name() .使用 local-name()就像您这样做(“摆脱 namespace ”)几乎总是被视为错误。声明命名空间并在您的 XPath 中使用它们,这样可以减少键入次数、不易出错并且更易于使用。

请注意,您不需要使用与输入中相同的前缀,只要您使用相同的命名空间 URI。在以下 XSL 片段中,我使用 se而不是 soapenv对于 SOAP Envelope 命名空间。
<xsl:transform version="1.0"
  xmlns:xsl=""
  xmlns:se="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:urn="urn:cidx:names:specification:ces:schema:all:5:0"
  exclude-result-prefixes="se urn"
>

  <!-- if you positively must be this specific -->
  <xsl:variable name="docId" select="/se:Envelope/se:Body/*/ThisDocumentIdentifier" />

  <!-- simpler/nicer is this -->
  <xsl:variable name="docId_nicer" select="//ThisDocumentIdentifier" />
</xsl:transform>

关于xml - Xpath 1.0 表达式获取任何请求的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30626595/

相关文章:

xml - 如何使用 LINQ to XML 包含 CData?

c++ - 如何设置QXmlStreamReader atStart?

java - 如何使用xpath dom java获取子节点的节点列表?

xml - XSLT 生成文件夹

selenium - 带有以下兄弟的 xpath

python - 使用python修改xml值文件

java - 使用 XYPlot 时如何解决问题 'Binary XML file line #8: Binary XML file line #8: Error inflating class com.androidplot.xy.XYPlot'

java - 如何使用 jdom 检查文件中是否存在元素

xpath - Watir:识别图像按钮

c# - 从 XHTML 文档中去除特定标签(但保留其内容)的机制?