xslt - 在两个XML文件中匹配ID并替换所有ID和名称

时间:2018-03-05 22:43:18

标签: xml xslt replace xsd xslt-2.0

我有2个XML文件,其中包含有关相同项目的数据,我只需要更改第一个XML中的ID。

1.xml第一个数据看起来像这样(有更多属性与比较无关):

 <channel id="Digi">
    <display-name lang="tr">Digi</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="Star">
    <display-name lang="tr">Star</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="ATV">
    <display-name lang="tr">ATV</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>

2.xml第二个数据看起来像这样(包含更多属性和可能的​​子元素):

 <channel id="Digi.TR">
    <display-name lang="tr">Digi.TR</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="Star.tr">
    <display-name lang="tr">Star.tr</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>
<channel id="ATV.tr">
    <display-name lang="tr">ATV.tr</display-name>
    <url>http://www.digiturk.com.tr</url>
  </channel>

是否可以运行一些脚本/代码/ xslt样式表来替换First 1.xml中的ID和来自Second Date 2.xml的ID?

我对样式表不是很熟悉,也不确定从哪里开始编写类似的东西

对于1.xml中的每个项目,读取属性“id”和“name”在2.xml中找到相同的“id”和“name”,在1.xml中替换“id”和“name”。

感谢您提供的任何帮助

1 个答案:

答案 0 :(得分:0)

假设两个XML都有一个根节点,例如调用<root>,每个包装XML内容。这对于XML格式良好是必要的,因为你的XML都不是。

现在First 1.xml已由身份模板复制,而复制所有相关的id属性节点时,将替换为{{1}中的相应id值使用Second Date 2.xml函数包含第二个XML文件。

要将第一个XML中的document()属性替换为第二个XML中的相应属性,请将每个对与谓词中的id进行比较。

starts-with()

<强>输出:

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

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

  <xsl:template match="channel/@id">
    <xsl:variable name="ID" select="." />    <!-- save @id from First 1.xml in variable $ID -->
    <xsl:attribute name="id">                <!-- reconstruct id attribute -->
        <!-- copy value from second XML to first XML if id attributes partially match -->
        <xsl:value-of select="normalize-space(document('Second Date 2.xml')/root/channel[starts-with(@id,$ID)]/@id)" />
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>