首页 > 解决方案 > xmlstarlet 根据属性选择值

问题描述

使用以下 file.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<config>
 <index type="I8">
  <book>2</book>
 </index>
</config>

我无法选择书

xmlstarlet sel --template --match /config/index[@type="I8"] -c . file.xml

我无法选择书

xmlstarlet sel --template --match /config/index[@type='I8'] -c . file.xml

我可以选择书

xmlstarlet sel --template --match "/config/index[@type='I8']" -c . file.xml

我可以选择书

xmlstarlet sel --template --match '/config/index[@type="I8"]' -c . file.xml

此外,如果 xml 中的 type 为 type="8",我可以选择它:

xmlstarlet sel --template --match /config/index[@type="8"] -c . file.xml

为什么?

xmlstarlet 1.6.1
compiled against libxml2 2.9.4, linked with 20904
compiled against libxslt 1.1.29, linked with 10129

标签: xmlxpathxmlstarlet

解决方案


这个有效(在 Windows 和 Ubuntu 上测试):

xmlstarlet sel -t -i /config/index/@type=\"I8\" -m //book -c . -b file.xml

它与引用有关,您可以在查看下一条语句的输出时了解原因:

xmlstarlet sel -C --template --match /config/index[@type="I8"] -c . file.xml

它的输出:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="/">
    <xsl:for-each select="/config/index[@type=I8]">
      <xsl:copy-of select="."/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

缺少引号I8


推荐阅读