【问题标题】:xpath select all attributes ending with foo?xpath 选择所有以 foo 结尾的属性?
【发布时间】:2017-08-12 05:55:32
【问题描述】:

XPATH/XSLT 1.0 是否可以选择所有以“Foo”结尾的属性?

我正在编写一些 XSLT 来获取属性名称以“Foo”结尾的所有“InterestingElement”的所有属性的所有值的列表。

其实我也想过滤掉那些值为空的""

我尝试为 XSLT 2.0 指定样式表,但得到了xsl:version: only 1.0 features are supported

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:fo="http://www.w3.org/1999/XSL/Format"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:fn="http://www.w3.org/2005/xpath-functions"
            xmlns:xdt="http://www.w3.org/2005/xpath-datatypes">

到目前为止我有:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:for-each select="//InterestingElement">
<xsl:value-of select="__what goes here?__"/><xsl:text>
</xsl:text>
</xsl:for-each>
<xsl:text>end</xsl:text>
</xsl:template>
</xsl:stylesheet>

这里有一些示例 XML:

<?xml version="1.0"?>
<root>
  <Other Name="Bob"/>
  <InterestingElements>
    <InterestingElement AttrFoo="want this"
                        Attr2Foo="this too"
                        Blah="not this"
                        NotThisFoo=""/>
  </InterestingElements>
</root>

【问题讨论】:

  • XSLT 1.0 还是 2.0?
  • 你也可以分享xml 示例、所需的输出和你已经尝试过的代码吗?

标签: xml xslt xpath xslt-1.0


【解决方案1】:

XPath 2.0 解决方案

XPath 2.0 可以单独解决这个问题;在 XSLT 2.0 中,不需要 xsl:for-each —— 只需 xsl:value-of

这个 XPath,

string-join(//InterestingElement/@*[ends-with(name(.), 'Foo') and . != ''], ' ')

将返回名称以Foo 结尾的所有InterestingElement 属性的(非空)值的空格分隔列表。

【讨论】:

  • 或者你也可以去掉string-join()并使用@separator&lt;xsl:value-of select="//InterestingElement/@*[ends-with(name(.), 'Foo') and . != '']" separator=" "/&gt;
  • @MadsHansen:好主意。
【解决方案2】:

XPath 1.0 解决方案

string-joinends-with 是 XPath 2.0。对于 1.0,您可以使用以下内容,它返回以空格分隔的所有值:

<xsl:for-each select="//InterestingElement/@*['Foo' = substring(name(.), string-length(name(.)) - string-length('Foo') +1) and . != '']">
  <xsl:value-of select="." /><xsl:text> </xsl:text>
</xsl:for-each>

要获取匹配的属性名称而不是值,请将选择更改为select="name(.)"

基于kjhughesanswerthis SO answer

【讨论】:

  • @user3735178 我忘记了 string-join 是 XSLT 2.0 ...我编辑了我的答案,把它放在了 &lt;xsl:for-each&gt; 中。
  • 可能是&lt;xsl:value-of select="node()" /&gt;&lt;xsl:text&gt; &lt;/xsl:text&gt;&lt;xsl:value-of select="node()/" /&gt;&lt;xsl:text&gt; &lt;/xsl:text&gt;,但我不能100% 确定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
相关资源
最近更新 更多