循环遍历地图对象并使用xsl转换修改xml

时间:2013-02-15 04:44:15

标签: xml xslt map

我有一个xml和Map对象,map包含一些关于xml节点的附加信息,即

<searchPersonResponse>
 <persons>
   <person>
     <id>123</id>
   </person>
   <person>
     <id>456</id>
   </person>
  </persons>
</searchPersonResponse>

我的地图是这样的 -

infoMap<123, <name="abc"><age="25">>
infoMap<456, <name="xyz"><age="80">>

我想要的输出是这样的: -

<searchPersonResponse>
 <persons>
  <person>
   <id>123</id>
   <name>abc</name>
   <age>25</age>
  </person>
  <person>
    <id>456</id>
    <name>xyz</name>
    <age>80</age>
   </person>
 </persons>
</searchPersonResponse>

我搜索了很多这样的样本/样本,但没有找到类似的样本。请帮忙 !!提前谢谢

1 个答案:

答案 0 :(得分:0)

因为您可以将所有内容放在同一个XML文件中,所以可以构建包含地图信息和数据的以下XML文件。

<xml>
    <!-- Original XML -->
    <searchPersonResponse>
        <persons>
            <person>
                <id>123</id>
            </person>
            <person>
                <id>456</id>
            </person>
        </persons>
    </searchPersonResponse>
    <!-- Map definition -->
    <map>
        <value id="123">
            <name>abc</name>
            <age>25</age>
        </value>
        <value id="456">
            <name>xyz</name>
            <age>80</age>
        </value>
    </map>
</xml>

现在您可以使用此样式表将XML文件转换为所需的输出:

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

    <xsl:output method="xml" indent="yes"/>

    <!-- Identity template : copy all elements and attributes by default -->
    <xsl:template match="*|@*">
        <xsl:copy>
            <xsl:apply-templates select="*|@*" />
        </xsl:copy>
    </xsl:template>

    <!-- Avoid copying the root element -->
    <xsl:template match="xml">
        <xsl:apply-templates select="searchPersonResponse" />
    </xsl:template>

    <xsl:template match="person">
        <!-- Copy the person node -->
        <xsl:copy>
            <!-- Save id into a variable to avoid losing the reference -->
            <xsl:variable name="id" select="id" />
            <!-- Copy attributes and children from the person element and the elements from the map-->
            <xsl:copy-of select="@*|*|/xml/map/value[@id = $id]/*" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
相关问题