难以编写XPATH以在XSLT中选择适当的节点

时间:2016-03-17 14:35:42

标签: xml xslt xpath

我很难获得xsl:apply-template选择只选择所需的元素。节点元素的以下每种形式都是有效的。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="node">
    <xsl:apply-templates select="node()[not(self::value)]"/>
  </xsl:template>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

我希望只选择具有“重要”内容的节点并避开其他节点。具有重要内容(asdf&amp; qwerty)的节点的名称对我来说是未知的,并且不能成为转换逻辑的一部分。

这是XSLT:

<?xml version="1.0" encoding="utf-8"?>
<root>unimportant
  <asdf>important</asdf>
  <qwerty>important</qwerty>
</root>

这是输出:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <asdf>important</asdf>
  <qwerty>important</qwerty>
</root>

预期结果如下

String.replace()

转换正在正确地选择所需的元素,但它也从第一个节点元素中获取不重要的内容。如何构造一个避免选择此内容的select语句?

3 个答案:

答案 0 :(得分:1)

假设您知道不喜欢哪些节点(not(self::value)) 改变你的

<xsl:apply-templates select="node()[not(self::value)]"/>

  <xsl:apply-templates select="*[not(self::value)]"/>

这将忽略错误的text()节点

答案 1 :(得分:0)

这对你有用吗?

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="/root">
    <xsl:copy>
        <xsl:apply-templates select="node[.='important'] | node/*[.='important']"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

答案 2 :(得分:-2)

echo "message to user" >&2

可替换地,

//node/*[not(self::value)]