XSLT “replace” values with another file matching b

2019-08-14 08:04发布

I want to know if it's possible to take the values for the same resources (same attribute value) from another file, maintaining in the first file all the structure and comments.

Maybe I'll explain it better with an example.

Input file 1 (the one that needs the values):

<?xml version="1.0" encoding="UTF-8"?>
<root>
     <element name="1">File1-value1</frag>
     <element name="2">File1-value2</frag>
     <element name="3">File1-value3</frag>
</root>

Input file 2 (the one to take the values from):

<?xml version="1.0" encoding="UTF-8"?>
<root>

     <element name="3">File2-value3</frag>
     <element name="7">File2-value3</frag>

     <element name="1">File2-value1</frag>
     <element name="2">File2-value2</frag>

</root>

Desired output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
     <element name="1">File2-value1</frag>
     <element name="2">File2-value2</frag>
     <element name="3">File2-value3</frag>
</root>

The point is to have all the contents of file 2 in file 1 for matching attributes (there will be extra elements with attribute values not present in file 1 that I don't want) but preserving order, tab structure, spaces and comments of file 1.

It may seem a very dumb process but there are a lot of big files. I have been reading a lot about XSLT but I could not found any solution as I'm completely novice with it.

Thank you very much for any possible answers.

标签: xml xslt
2条回答
Evening l夕情丶
2楼-- · 2019-08-14 09:01

Xslt 2.0

<xsl:key name="k1" match="element" use="@name"/>

<xsl:param name="lkp-url" select="'lookup.xml'"/>

<xsl:variable name="lkp-doc" select="doc($lkp-url)"/>

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* , node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="element[@name and key('k1', @name, $lkp-doc)]">
  <xsl:copy>
    <xsl:copy-of select="@* , key('k1', @name, $lkp-doc)/node()"/>
  </xsl:copy>
</xsl:template>
查看更多
可以哭但决不认输i
3楼-- · 2019-08-14 09:05

For any newbies, like me, who are struggling to run this, a few amendments are required. All elements named element needs </frag> to be replaced with </element>

And, for me, the chosen answer needs to be encapsulated with:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 ....
 </xsl:stylesheet>
查看更多
登录 后发表回答