使用xmlStarlet工具在XML文件中获取值

时间:2017-03-17 08:23:22

标签: xml bash shell xslt xmlstarlet

我的XML文件结构

<properties>
    <structure name="preference">
        <structure name="cam">
            <property name="number" value="8"/>
            <property name="name" value="eddi"/>
        </structure>
    </structure>
</properties>

使用XMLstarlet工具,我试图获得值“ 8 ”,所以我首先尝试了以下命令:

xmlstarlet -t -v '/properties/structure[@name="preference"]/structure[@name="cam"][property/@name="number"]/@value' file.xml

然后我得到了这些错误:

  

解析器错误:属性构造错误
    xsl:value-of select =“/ properties / structure [@ name =”preference“]

     

解析器错误:无法找到第23行的开始标记值的结尾     xsl:value-of select =“/ properties / structure [@ name =”preference“]

这些错误指向“偏好” 我看到了一些涉及这种行为的主题,但他们的解决方案与我的案例不符。

您对如何获得此值有任何想法吗?

1 个答案:

答案 0 :(得分:1)

对于更新的(通过@ har07)和有效的xml,例如:

<properties>
    <structure name="preference">
        <structure name="cam">
            <property name="number" value="8"/>
            <property name="name" value="eddi"/>
        </structure>
    </structure>
</properties>

(注意自闭标签/>

你可以使用:

xmlstarlet sel -T -t -m '//property[@name="number"]/@value' -v . -n file.xml

并打印

8

使用:

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