Search code examples
xmlbashshellxsltxmlstarlet

get value in an XML file with xmlStarlet tool


My XML file structure

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

With XMLstarlet tool, I'm trying to get the value "8" so I first tried this following command:

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

Then I get these errors:

parser error : attributes construct error
xsl:value-of select="/properties/structure[@name="preference"]

parser error : Couldn't find end of Start Tag value-of line 23
xsl:value-of select="/properties/structure[@name="preference"]

these errors are pointing to "preference".
I saw some topics dealing with this kind of action but their solution doesn't match with my case.

Do you have any idea on how to get this value?


Solution

  • For the updated (by @har07) and valid xml, e.g.:

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

    (Note the self closing tags />)

    you could use:

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

    and prints

    8
    

    using:

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