joy joy - 1 month ago 17
Bash Question

Convert xml into simple file using xslt unix

I am having one xml file (test.xml) looks like this:

<hudson>
<job>
<name>cedge</name>
</job>
<job>
<name>techM</name>
</job>
<job>
<name>infy</name>
</job>
<job>
<name>DevP</name>
<job>
<name>line</name>
<nextBuildNumber>14</nextBuildNumber>
</job>
<job>
<name>ment</name>
<nextBuildNumber>85</nextBuildNumber>
</job>
<job>
<name>FreeS</name>
<nextBuildNumber>96</nextBuildNumber>
</job>
<job>
<name>test</name>
</job>
</job>
<job>
<name>Email</name>
</job>
<job>
<name>investigate</name>
<nextBuildNumber>26</nextBuildNumber>
</job>
<job>
<name>Java</name>
</job>
<job>
<name>Tools</name>
</job>
</hudson>


need output file like:

"line" "14"
"ment" "85"
"FreeS" "96"
"investigate" "26"


trying with below approch

xsltproc x.xslt test.xml


made x.xslt like this:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//job">
"<xsl:value-of select="name"/>" = "<xsl:value-of select="nextBuildNumber"/>"
</xsl:template>
</xsl:stylesheet>


getting only

"investigate" = "26"


along with blank values. Not getting data from "job-Devp" tags
any help would be appriciated.

Answer

Your XSLT doesn't quite produce the output you say you get, as it will also output lines for all job elements directly under the root hudson, like this..

 "cedge" = ""

Additionally, when you match the job element, you are not continuing processing by selecting any descendant job elements of those, so the nested job elements do not get picked up.

Probably the easiest thing to do is simply add a template that matches the document node \ and specifically select all the job elements you need (i.e the ones with nextBuildNumber

Try this XSLT

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output method="text" />

 <xsl:template match="/">
     <xsl:apply-templates select="//job[nextBuildNumber]" />
 </xsl:template>

 <xsl:template match="job">
    <xsl:text>"</xsl:text>
    <xsl:value-of select="name"/>
    <xsl:text>" = "</xsl:text>
    <xsl:value-of select="nextBuildNumber"/>
    <xsl:text>"&#10;</xsl:text>
 </xsl:template>
 </xsl:stylesheet>
Comments