pankaj_ar
pankaj_ar

Reputation: 765

xmllint give attribute only if elements are present unix

I have an XML as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<tns:myproject>
<tns:site name="London"/>
<tns:site name="Paris"/>
<tns:site name="New York"/>

<tns:node hostname="S1" IP="10.10.10.1" siteid="London">
        <tns:elements>
        <tns:database/>
    </tns:elements>
</tns:node>
<tns:node hostname="S1" IP="10.10.10.2" siteid="London">
    <tns:elements>
        <tns:admin/>
    </tns:elements>
</tns:node>

<tns:node hostname="S2" IP="10.10.10.3" siteid="Paris">
        <tns:elements>
        <tns:database/>
    </tns:elements>
</tns:node>
<tns:node hostname="S2" IP="10.10.10.4" siteid="Paris">
    <tns:elements>
        <tns:admin/>
    </tns:elements>
</tns:node>

<tns:node hostname="S3" IP="10.10.10.5" siteid="New York">
        <tns:elements>
        <tns:database/>
    </tns:elements>
</tns:node>
<tns:node hostname="S3" IP="10.10.10.6" siteid="New York">
    <tns:elements>
        <tns:admin/>
    </tns:elements>
</tns:node>
</tns:myproject>

I need the values hostname, IP and siteid if the element database is present in node.

Expected output:

hostname="S1" IP="10.10.10.1" siteid="London"
hostname="S2" IP="10.10.10.2" siteid="Paris"
hostname="S3" IP="10.10.10.3" siteid="New York"

I am new to xmllint, so I tried few commands in unix like

xpath project.xml "//@hostname" or echo 'cat //@hostname' | xmllint --shell "topo.p.xml"

But don't know how can I filter it based on tag database.

Upvotes: 0

Views: 740

Answers (1)

har07
har07

Reputation: 89295

Basically, you can use xpath predicate ([]) to filter element. Assume that your XML doesn't have namespace prefix involved, the following xpath will get hostname attribute from <node> element having descendant element <database>:

//node[elements/database]/@hostname

Since your actual XML has prefix involved you need to declare namespace prefix first, probably using stns command (I'm not xmllint user) :

xmllint --shell project.xml
stns tns=uri.for.tns.here.according.to.your.xml

Then use the registered prefix in your xpath :

//tns:node[tns:elements/tns:database]/@hostname

Upvotes: 1

Related Questions