
Question:
I've searched for a solution for my problem. I found some similar questions and answers but none of them fitted to my problem.
I'm an XML newbie and never used XSLT before. I have Linux and could use xsltproc or xmllint (or whatever would be best).
The problem is rather easy. I have to XML files with identical layout. At the beginning is a counter for the nodes included in one file. I just need the counters of both files added and then all nodes from both files as a single list. (Sorted would be even better.)
Example: a.xml
<?xml version="1.0" standalone="yes"?>
<List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/List.xsd">
<publshInformation>
<Publish_Date>12/17/2014</Publish_Date>
<Record_Count>115</Record_Count>
</publshInformation>
<Entry>
<uid>9639</uid>
<firstName>Bob</firstName>
....
</Entry>
</List>
b.xml
<?xml version="1.0" standalone="yes"?>
<List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/List.xsd">
<publshInformation>
<Publish_Date>12/17/2014</Publish_Date>
<Record_Count>100</Record_Count>
</publshInformation>
<Entry>
<uid>4711</uid>
<firstName>John</firstName>
....
</Entry>
</List>
Result: out.xml
<?xml version="1.0" standalone="yes"?>
<List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/List.xsd">
<publshInformation>
<Publish_Date>12/17/2014</Publish_Date>
<Record_Count>215</Record_Count>
</publshInformation>
<Entry>
<uid>4711</uid>
<firstName>John</firstName>
....
</Entry>
<Entry>
<uid>9639</uid>
<firstName>Bob</firstName>
....
</Entry>
</List>
How can I manage that? I don’t post my XSLTs here because they are not working and that’s because of my limited skills. Thanks for any suggestions!
Answer1:Try it this way. The idea here is that you apply the XSL transformation to document a.xml
, and pass the path to the b.xml
file as a parameter.
You will probably want to change the node/s to sort on to something more reasonable.
Note the use of a prefix to address the nodes in your XML sources, since they are all in a namespace.
<strong>XSLT 1.0</strong>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="http://tempuri.org/List.xsd">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="doc2" select="'b.xml'" />
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="ns1:Record_Count">
<xsl:copy>
<xsl:value-of select=". + document($doc2)/ns1:List/ns1:publshInformation/ns1:Record_Count" />
</xsl:copy>
</xsl:template>
<xsl:template match="ns1:List">
<xsl:copy>
<xsl:apply-templates select="*|document($doc2)/ns1:List/ns1:Entry">
<xsl:sort select="ns1:firstName" data-type="text" order="ascending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>