使用xmlstarlet上的xpath检索XML元素的所有属性名称

时间:2015-01-26 10:30:30

标签: xml xpath xmlstarlet

我可以看到如何检索所有属性值:
xml sel -t -v "//element/@*"

但我希望得到所有属性名称 我可以获得第n个名称,例如xml sel -t -v "name(//x:mem/@*[3])",它返回第3个属性名称 但是xml sel -t -v "name(//x:mem/@*)"不起作用(仅返回第一个属性名称)...

有没有办法获取所有属性名称?

2 个答案:

答案 0 :(得分:3)

此xmlstarlet命令:

xml tr attnames.xsl in.xml

使用此XSLT转换,名为attnames.xsl:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:template match="@*">
    <xsl:value-of select="name(.)"/>
    <xsl:text>&#xa;</xsl:text>
  </xsl:template>
  <xsl:template match="*">
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="*"/>
  </xsl:template>
</xsl:stylesheet>

此XML文件名为in.xml:

<root att1="one">
  <a att2="two"/>
  <b att3="three">
    <c att4="four"/>
  </b>
</root>

将生成in.xml中找到的所有属性的列表:

att1
att2
att3
att4

要仅从b元素中选择所有属性,请像这样修改XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:template match="@*">
    <xsl:value-of select="name(.)"/>
    <xsl:text>&#xa;</xsl:text>
  </xsl:template>
  <xsl:template match="b">
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="*"/>
  </xsl:template>
  <xsl:template match="text()"/>
</xsl:stylesheet>

答案 1 :(得分:3)

使用-t-m定义模板匹配,然后使用-v应用另一个XPath表达式。

$ xml sel -T -t -m "//mem/@*" -v "name()" -n input.xml

应用于此输入XML时:

<root>
    <mem yes1="1" yes2="2"/>
    <other no="1" no2="2"/>
</root>

将打印:

yes1
yes2

这是shell&#34;上的短线,但它完全无法理解。因此,我仍然更喜欢kjhughes&#39; XSLT解决方案。不要为了简洁而牺牲可理解的代码。

您可以编写一个从命令行获取输入参数的样式表,这样,如果您想要检索其他元素的属性名称,则无需更改XSLT代码。


正如@npostavs在内部所建议的,xmlstarlet无论如何都使用了XSLT。您可以通过将-T替换为-C来检查生成的XSLT:

$ xml sel -C -t -m "//mem/@*" -v "name()" -n app.xml

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exslt="http://exslt.org/common" version="1.0" extension-element-prefixes="exslt">
  <xsl:output omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="/">
    <xsl:for-each select="//mem/@*">
      <xsl:call-template name="value-of-template">
        <xsl:with-param name="select" select="name()"/>
      </xsl:call-template>
      <xsl:value-of select="'&#10;'"/>
    </xsl:for-each>
  </xsl:template>
  <xsl:template name="value-of-template">
    <xsl:param name="select"/>
    <xsl:value-of select="$select"/>
    <xsl:for-each select="exslt:node-set($select)[position()&gt;1]">
      <xsl:value-of select="'&#10;'"/>
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

还有更多选项需要探索,请参阅xmlstarlet documentation

相关问题