2016-10-10 80 views
1

我有XML,我需要转换为更简化的格式。我确信这可以用XSLT完成,但我不确定如何。在输出元素名称是动态的地方转换XML?

我需要转换:

<Fields> 
    <Field> 
    <Name>Element1</Name> 
    <Value>Value 1</Value> 
    </Field> 
    <Field> 
    <Name>Element2</Name> 
    <Value>Value 2</Value> 
    </Field> 
</Fields> 

<Fields> 
    <Element1>Value 1</Element1> 
    <Element2>Value 2</Element2> 
</Fields> 

这是我目前:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@* | node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="/*"> 
    <xsl:copy> 
     <xsl:copy-of select="Fields/Field/*"/> 
     <xsl:apply-templates select="*[name()]"/> 
    </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

回答

1

您输入XML,

<Fields> 
    <Field> 
    <Name>Element1</Name> 
    <Value>Value 1</Value> 
    </Field> 
    <Field> 
    <Name>Element2</Name> 
    <Value>Value 2</Value> 
    </Field> 
</Fields> 

通过该XSLT转换,

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="Fields"> 
    <xsl:copy> 
     <xsl:apply-templates/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="Field"> 
    <xsl:element name="{Name}"> 
     <xsl:value-of select="Value"/> 
    </xsl:element> 
    </xsl:template> 
</xsl:stylesheet> 

产生这个输出XML,

<?xml version="1.0" encoding="UTF-8"?> 
<Fields> 
    <Element1>Value 1</Element1> 
    <Element2>Value 2</Element2> 
</Fields> 

的要求。

+1

*重要*注意:有有效的xml元素名称的规则。 (1)姓名不得以数字开头。 (2)名称不能以特殊字符(如连字符或句点)开头。 (3)名称不能包含除句点,连字符,下划线和冒号以外的特殊字符。 – uL1

+0

您可以使用双翻译方法 - '来防止无效名称, $ validChars'是一个变量,它包含您想要在名称中允许的所有字符。这虽然有点粗糙。 – Flynn1179