Warm tip: This article is reproduced from serverfault.com, please click

xslt-包含来自另一个文件的xml和来自父文件的内容

(xslt - Include xml from another file with contents from parent file)

发布于 2020-12-01 19:03:43

是否可以将另一个xml文件(子xml)的内容插入到具有更新属性的父xml中-严格使用xml或xslt?还是我必须使用python来生成xml。

例如,假设我有一个包含内容的父xml:

<root>
    <parent1 value="parent1">
        # get contents of child.xml
    </parent1>
    <parent2 value="parent2">
        # get contents of child.xml
    </parent2>
</root>

child.xml具有以下内容:

<root>
    <child1 value="child1"/>
    <child2 value="child2"/>
</root>

我可以用include来做,但是我也想更新它的值。所以我想要的最终xml是:

<root>
    <parent1 value="parent1">
        <child1 value="parent1_child1"/>
        <child2 value="parent1_child2"/>
    </parent1>
    <parent2 value="parent2">
        <child1 value="parent2_child1"/>
        <child2 value="parent2_child2"/>
    </parent2>
</root>

子项的值根据父项值进行更新。

Questioner
user1179317
Viewed
11
Sebastien 2020-12-02 03:28:25

你可以使用document()函数来引用另一个XML文件。你可以这样实现它。

<?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"/>
  
  <xsl:variable name="childDoc" select="document('child.xml')"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="parent">
    <xsl:variable name="currentParent" select="."/>
    <xsl:copy>
      <xsl:for-each select="$childDoc/root/child">
        <xsl:copy>
          <xsl:attribute name="value" select="concat($currentParent/@value,'_',@value)"/>
        </xsl:copy>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
  
</xsl:stylesheet>

看到它在这里工作:https : //xsltfiddle.liberty-development.net/pNvtBGr (出于测试目的,我已将文档放在变量中。)