Home > Enterprise >  Display multiple elements of an XML
Display multiple elements of an XML

Time:12-05

I have an xml file with multiple elements with the same key elements with the same name. I'm trying to concatonate the sub elements but can only get the first occurrence.

<?xml version="1.0" encoding="utf-8"?>
<FOLDER JOBNAME="some Job"  MAXWAIT="5">
    <OTHER>
        <ELEMENTS>
        </ELEMENTS>
    </OTHER>
</FOLDER>
<FOLDER JOBNAME="some Other Job"  MAXWAIT="15">
    <OTHER>
        <ELEMENTS>
        </ELEMENTS>
    </OTHER>
</FOLDER>

Is there a way to use xmllint or some other tool to get output like:

some Job 5
some Other Job 15
etc...

when I try with xmllint --xpath, I get the following:

me@myComp tmp $ xmllint --xpath 'concat(//@JOBNAME," ",//@MAXWAIT)' jobs.xml
ADDRESS_VERIFICATION 5
me@myComp tmp $ xmllint --xpath 'concat(//JOBNAME[*]," ",//MAXWAIT[*])' jobs.xml
 
me@myComp tmp $ 

Is there a way to concatenate multiple parameters with xmllint or any other tool on the command line?

UPDATE - Yeah, it's a proper XML - Also, just notices the repeated lines and removed them.

CodePudding user response:

Assuming you have valid XML (per comments by @GillesQuenot and @Cyrus) and are open to using XSLT, then the following transform might be an option:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" encoding="UTF-8" />
    <xsl:template match="FOLDER">
        <xsl:value-of select="concat(@JOBNAME, ' ', @MAXWAIT)"/>
    </xsl:template>
</xsl:transform>

Sample usage:

$ xsltproc abc.xslt abc.txt

some Job 5
some Other Job 15

CodePudding user response:

You may find the XML parser interesting:

$ xidel -s jobs.xml -e '//FOLDER/concat(@JOBNAME," ",@MAXWAIT)'
$ xidel -s jobs.xml -e '//FOLDER/join((@JOBNAME,@MAXWAIT))'
$ xidel -s jobs.xml -e '//FOLDER/x"{@JOBNAME} {@MAXWAIT}"'   # Xidel's own extended-string-syntax.

All resulting in:

some Job 5
some Other Job 15
  • Related