Search code examples
xpathcmdxmlstarlet

XMLStarlet doesn't select xpath query correctly


I have the following XML

<?xml version='1.0' encoding='UTF-8'?>
<ListBucketResult xmlns='http://doc.s3.amazonaws.com/2006-03-01'>
    <Name>chromedriver</Name>
    <Prefix></Prefix>
    <Marker></Marker>
    <IsTruncated>false</IsTruncated>
    <Contents>
        <Key>2.0/chromedriver_linux32.zip</Key>
        <Generation>1380149859530000</Generation>
        <MetaGeneration>4</MetaGeneration>
        <LastModified>2013-09-25T22:57:39.349Z</LastModified>
        <ETag>"c0d96102715c4916b872f91f5bf9b12c"</ETag>
        <Size>7262134</Size>
    </Contents>
    <Contents>
        <Key>2.0/chromedriver_linux64.zip</Key>
        <Generation>1380149860664000</Generation>
        <MetaGeneration>4</MetaGeneration>
        <LastModified>2013-09-25T22:57:40.449Z</LastModified>
        <ETag>"858ebaf47e13dce7600191ed59974c09"</ETag>
        <Size>7433593</Size>
    </Contents>
    ...
</ListBucketResult>

And I tried select only Key node with this command:

xmlstarlet sel -T -t -m '/ListBucketResult/Contents/Key' -v '.' -n file.xml

I tried some commands, but none return any value

And I tried el to see the scructure:

xmlstarlet el file.xml
ListBucketResult
ListBucketResult/Name
ListBucketResult/Prefix
ListBucketResult/Marker
ListBucketResult/IsTruncated
ListBucketResult/Contents
ListBucketResult/Contents/Key
ListBucketResult/Contents/Generation
ListBucketResult/Contents/MetaGeneration
ListBucketResult/Contents/LastModified
ListBucketResult/Contents/ETag
ListBucketResult/Contents/Size

I don't know what is incorrect


Solution

  • Your XML elements are bound to the namespace http://doc.s3.amazonaws.com/2006-03-01, but your XPath is not referencing any namespaces (not using a namespace-prefix). So, it is attempting to reference elements in the "no namespace" and finding nothing.

    You need to declare that namespace with a namespace-prefix using the -N switch, and use the namespace-prefix in your XPath:

    xmlstarlet sel -N s3="http://doc.s3.amazonaws.com/2006-03-01" -T -t -m '/s3:ListBucketResult/s3:Contents/s3:Key' -v '.' -n file.xml
    

    Reference: http://xmlstar.sourceforge.net/doc/UG/ch05s01.html