如何创建一个访问属性文件的xsl文件,以便进行xml到xml文件的转换

时间:2012-03-30 06:56:02

标签: xslt properties

将xml文件视为

<Content>
  <abc>....</abc>
</Content>

我有一个假设

的属性文件
 abc=def

我最终转换的xml文件看起来像

<Content>
  <def>....</def>
</Content>

所以我的xsl文件转换第一个xml文件应该使用上面的属性文件并对其进行转换。任何人都可以建议我们如何使用XSLT实现这个目标?

1 个答案:

答案 0 :(得分:0)

如果以XML格式存储属性文件,例如

<Properties>
    <Property value="abc">def</Property>
    <Property value="...">...</Property>
</Properties>

然后你可以使用xslt处理两个XML文件并用def的替换abc元素,等等。

例如

<?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" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:variable name="props" select="document('Properties.xml')"/>

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

    <xsl:template match="Content/*">
        <xsl:variable name="repl" select="$props/Properties/Property[@value=name(current())]"/>
        <xsl:choose>
            <xsl:when test="$repl">
                <xsl:element name="{$repl}">
                    <xsl:apply-templates/>
                </xsl:element>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

适用于

<?xml version="1.0" encoding="UTF-8"?>
<Content>
  <abc>xxx</abc>
  <def>zzz</def>
  <ghi>ccc</ghi>
</Content>

使用属性文件

<?xml version="1.0" encoding="UTF-8"?>
<Properties>
    <Property value="abc">def</Property>
    <Property value="def">www</Property>
</Properties>

这导致

<?xml version="1.0" encoding="UTF-8"?>
<Content>
    <def>xxx</def>
    <www>zzz</www>
    <ghi>ccc</ghi>
</Content>

Jeevan的补充

------------------------------------------------------------------------------------ 
      My question is that if i want to access 
         'value' attribute(input xml file tags) 

     ex:       
                  <Property value="abc">def</Property>

我希望从另一个变量'repl1'中的Properties.xml文件中访问'abc',在select中使用'$ props / Properties / ..'之类的东西? 如何实现这一目标。

Maestro13的答案

还不清楚你想做什么,所以我会给你一些希望有用的提示。

可以通过包含/@value的Xpath表达式访问value属性。当然,您需要有一个当前的Property节点。这可以通过如下循环来完成:

<xsl:for-each select="$props/Properties/Property">
    <w><xsl:value-of select="@value"/></w>
</xsl:for-each>

其中循环中的当前节点是循环的节点,@value作用于该节点 或者您可以定义一个模板(模板,除非直接命名和调用,否则将为所有匹配节点重复调用)。
另一种检索value属性的方法是首先有一个Xpath表达式,它只选择一个Property元素,例如通过选择第n个匹配项,如下所示:

<xsl:value-of select="$props/Properties/Property[3]/@value"/>

如果是上述属性文件,则会返回ghi