user1582375
user1582375

Reputation: 43

XMLStarlet - For each <name> element

I have the following XML.

<application>
<name>Activity Monitor.app</name>
<path>/Applications/Utilities/Activity Monitor.app</path>
<version>10.8.0< /version></application>
<application>
<name>Adobe Flash Player Install Manager.app</name>
<path>/Applications/Utilities/Adobe Flash Player Install Manager.app</path>
<version>11.3.300.268</version></application>

Using XMLStarlet, I'd like to get the following output:

<package name="Activity Monitor.app">
<attribute name="Path">/Applications/Utilities/Activity Monitor.app</attribute>
<attribute name="Ver">10.8.0</attribute >
<package name="Adobe Flash Player Install Manager.app">
<attribute name="Path">/Applications/Utilities/Adobe Flash Player Install Manager.app</attribute>
<attribute name="Ver">11.3.300.268</attribute>

I've tried the command:

xml sel -t  -v "computer/software/applications/application/path" -v "computer/software/applications/application/name" -v computer/software/applications/application/version

but this is simply listing all the application then all the paths then all version. I am an XMLStarlet novice so I'd appreciate any/all help! Thanks!

Upvotes: 0

Views: 1852

Answers (1)

pbrc
pbrc

Reputation: 114

I am afraid the easiest way of getting what you want is to write a xsl transformation similar to this one:

<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="application">
     <package>
       <xsl:attribute name="name">
         <xsl:value-of select="name"/>
       </xsl:attribute>
       <xsl:apply-templates/>
     </package>
   </xsl:template>

   <xsl:template match="path|version">
     <attribute>
       <xsl:attribute name="name">
         <xsl:value-of select="name()"/>
       </xsl:attribute>
       <xsl:value-of select="text()"/>
     </attribute>
   </xsl:template>

   <xsl:template match="text()"/>

</xsl:stylesheet>

You can then use xmlstarlet to do the transformation:

xml tr thetransformation.xsl source.xml

I always found this tutorial quite helpful for things like that: http://zvon.org/xxl/XSLTutorial/Output/contents.html#id8

Upvotes: 1

Related Questions