【发布时间】:2017-09-22 17:12:00
【问题描述】:
我试图通过动态创建 xpath 来获取 xml 节点的属性值。但它一直在返回空值。如果我对 xpath 进行硬编码,它可以正常工作。下面是一个示例 xml 文件:
<root>
<PR id="id6016" name="OUTER WORLD">
<ADS id="id6017" dsRef="#id15" role="form1">
</ADS>
<ADS id="id6018" dsRef="#id9" role="form1">
</ADS>
</PR>
<PR id="id1000" name="OUTER WORLD">
<ADS id="id1001" dsRef="#id16" role="form1">
</ADS>
<ADS id="id1002" dsRef="#id10" role="form1">
</ADS>
</PR>
<DS id="id9" name="form1" version="7" type="CAD">
</DS>
<DS id="id15" name="form1" version="1" type="MSWord">
</DS>
<DS id="id10" name="form1" version="1" type="CAD">
</DS>
<DS id="id16" name="form1" version="1" type="MSWord">
</DS>
</root>
我的示例 xsl 是:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="no" indent="no" encoding="utf-8"/>
<xsl:template match="/root">
<result>
<xsl:apply-templates select="PR" mode="PR" />
</result>
</xsl:template>
<xsl:template match="PR" mode="PR">
<PR>
<xsl:attribute name="id">
<xsl:value-of select="@id" />
</xsl:attribute>
<xsl:attribute name="name">
<xsl:value-of select="@name" />
</xsl:attribute>
<xsl:for-each select="ADS[@role='form1']">
<DS>
<xsl:attribute name="id">
<xsl:value-of select="string(substring-after(@dsRef, '#'))" />
</xsl:attribute>
<xsl:value-of select="../DS[@id=string(substring-after(@dsRef, '#'))]/@type" />
</DS>
</xsl:for-each>
<DS2>
<xsl:value-of select="../DS[@id='id9']/@type" />
</DS2>
<DS3>
<xsl:value-of select="../DS[@id=string(substring-after(@dsRef, '#'))]/@type" />
</DS3>
</PR>
</xsl:template>
</xsl:stylesheet>
如您所见,我得到了 DS2 标记的任何内部文本,但 DS 或 DS3 没有。我还在 DS 标记中添加了 id 属性,以表明我得到的 id 是好的。
最终我想过滤具有 type="CAD" 的 DS 标记并将其 id 存储在一个变量中,但现在我无法使用 xpath 获取 xml 节点,所以我被卡住了。
【问题讨论】: