0

In response to a curl command curl -ik -u max:pass -X GET -i -H "Content-Type: application/xml" https://1.2.3.4:943/cloud/rest/projects I get a huge xml with many entires similar to the following

<project xlink:href="https://1.2.3.4:943/cloud/projects/13389/" >
            <approvedservers xlink:href="https://1.2.3.4:943/cloud/projects/13389/approvedservers/" ></approvedservers>
            <requestUser>maxadmin</requestUser>
            <removed xlink:href="https://1.2.3.4:943/cloud/projects/13389/removed/" ></removed>
            <rejected>false</rejected>
            <pending xlink:href="https://1.2.3.4:943/cloud/rest/projects/13389/pending/" ></pending>
            <name>4BSm3ZQ1T6q7xBR2xT2PdQ</name>
            <servers xlink:href="https://1.2.3.4:943/cloud/rest/projects/13389/servers/" ></servers>
            <ticketId>ticketId</ticketId>
            <approved>true</approved>
            <history xlink:href="https://1.2.3.4:943/cloud/rest/projects/13389/history/" ></history>
            <startTime>1502214154651</startTime>
            <requestedServerCount>1</requestedServerCount>
            <applicationid>4336525</applicationid>
            <provision>provision</provision>
            <customer>None</customer>
            <endTime>253402300740000</endTime>
        </project>

How can I parse this output to fetch project ID which is same in all the urls https://1.2.3.4:943/cloud/rest/projects/13389/pending/ based on the <name>4BSm3ZQ1T6q7xBR2xT2PdQ</name>. Basically I want to find the project id for a user name.

codec
  • 7,978
  • 26
  • 71
  • 127
  • Is it possible to get with content type as `json`, that way it can be easily parsed using `jq`? Can you try with `"Content-Type: application/json"`? using this answer https://stackoverflow.com/questions/21326397/curl-get-request-with-json-parameter – Inian Aug 23 '17 at 10:02

1 Answers1

1

You could use xmlstarlet and search for all name elements that have the desired text as value, then output the sibling element pending (using ../pending/@href:xlink which means "up one level, then element pending, then attribute xlink:href):

xmlstarlet sel -t  --match '//name[text() = "4BSm3ZQ1T6q7xBR2xT2PdQ"]' -v "../pending/@xlink:href"   file.xml
Arminius
  • 1,029
  • 7
  • 11
  • You can specify the condition in the xpath: `-v "//project[name='$name']/@xlink:href"` – glenn jackman Aug 23 '17 at 12:01
  • 1
    @glennjackman yes, that's better. If I don't use `xmlstarlet` on a daily basis, I forget everything :-) – Arminius Aug 23 '17 at 12:22
  • Too true. I have to do `xmlstarlet sel --help | less` every single time. Wait until you start using [tag:jq] though... – glenn jackman Aug 23 '17 at 12:30
  • @glennjackman oh, `jq` the tool that makes `xmlstarlet` and exiting `vim` look easy :-) -- that's where the gray hair on the left side of my head is from ... – Arminius Aug 23 '17 at 12:34