如何编写一个 xpath 来选择一个节点,其文本包含特殊字符,例如 ' 这是一种无效的 inxpath?
<Nodes><Node><Text>General Marketing'</Text><Nodes><Node><Text>Brochures</Text></Node><Node><Text>Value-Added</Text><Nodes><Node><Text>About Henderson</Text></Node><Node><Text>Own the World</Text></Node></Nodes></Node></Nodes></Node></Nodes>
和
var branchName = "General Marketing'";
var xPath = String.Format("/Nodes/Node[Text = '{0}']", branchName);
上述 xpath 失败,因为 xPath 包含以下文本:
/Nodes/Node[Text = 'General Marketing'']
如您所见,有 2 个撇号。
到目前为止,从我的测试来看,只有 '.不确定是否有任何其他特殊字符可能有问题?
所以我想我需要将我的 xpath 修改为其他内容。
我尝试了以下但没有成功:
var xPath = String.Format("/Nodes/Node[Text = \"{0}\"]", branchName);
希望问题清楚。
谢谢,
最佳答案
使用:
//Text[.="General Marketing'"]
如果在 XSLT 中使用此 XPath 表达式,则整个 XPath 表达式必须用撇号包围,并且引号包围的字符串的最后一个字符(撇号)必须使用内置实体 '
:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select='//Text[.="General Marketing'"]'/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 XML 文档时:
<Nodes>
<Node>
<Text>General Marketing'</Text>
<Nodes>
<Node>
<Text>Brochures</Text>
</Node>
<Node>
<Text>Value-Added</Text>
<Nodes>
<Node>
<Text>About Henderson</Text>
</Node>
<Node>
<Text>Own the World</Text>
</Node>
</Nodes>
</Node>
</Nodes>
</Node>
</Nodes>
想要的元素被选中并复制到输出:
<Text>General Marketing'</Text>
这比其他方法更简单,例如:
//Text[. = concat('General Marketing', $vQ)]
其中变量 $vQ
定义为:
<xsl:variable name="vQ">'</xsl:variable>
关于xml - 如何编写 xpath 来选择文本中包含特殊字符(如撇号)的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945063/