Xmlstarlet by selecting node with specific attribute value

I'm new to all of this, so please forgive me if the answer is completely obvious! I have an XML document that I downloaded from NCBI and I am trying to extract host information from each record that looks a little something like this (but much more deeply nested):

<OrgName_mod>
    <OrgMod>
        <OrgMod_subtype value="strain">2</OrgMod_subtype>
        <OrgMod_subname>Mvs/Jiroft.IRN/14.15/1[B3]</OrgMod_subname>
    </OrgMod>
    <OrgMod>
        <OrgMod_subtype value="nat-host">21</OrgMod_subtype>
        <OrgMod_subname>Homo sapiens</OrgMod_subname>
    </OrgMod>
</OrgName_mod>

      

I had success using the following:

xml sel -t -v //OrgName_mod/OrgMod[2]/OrgMod_subname -n file.xml

      

But the problem is that sometimes there is more or less information in the OrgMod nodes and the host is not always in the second position. So I've tried almost every version of this to try and select the host node in particular:

xml sel -t -m //OrgMod/OrgMod_subtype[@value=nat-host] -v ../OrgMod_subname -n file.xml

      

I want to select the OrgMod_subtype node with nat-host attribute and then afterwards print the username (?) Of the OrgMod_subname node with the view name.

Any help would be much appreciated!

+3


source to share


2 answers


Try this way:



 //OrgMod[OrgMod_subtype/@value = 'nat-host']/OrgMod_subname/text()

      

+3


source


From what I can see, the only way to pass on a sibling is by going to his parents. For example, the following error is a bug when I tested:

$ xmlstarlet sel -t -m "//OrgMod/[OrgMod_subtype/@value='nat-host']/OrgMod_subname/text()" file.xml
Invalid expression: //OrgMod/[OrgMod_subtype/@value='nat-host']/OrgMod_subname/text()
compilation error: element for-each
xsl:for-each : could not compile select expression '//OrgMod/[OrgMod_subtype/@value='nat-host']/OrgMod_subname/text()'

      

So, I improvised going down with ../ and this works:



$ xmlstarlet sel -t -m "//OrgMod/OrgMod_subtype[@value='nat-host']" -v "../OrgMod_subname/text()" file.xml
Homo sapiens~
$

      

My xmlstarlet version :

$ xmlstarlet --version
1.6.1
compiled against libxml2 2.9.1, linked with 20904
compiled against libxslt 1.1.28, linked with 10129
$

      

0


source







All Articles