转换输出元素名称为动态的XML?
我需要将XML转换为更简化的格式。我确信这可以通过XSLT实现,但我不确定如何实现 我需要转换:转换输出元素名称为动态的XML?,xml,xslt,Xml,Xslt,我需要将XML转换为更简化的格式。我确信这可以通过XSLT实现,但我不确定如何实现 我需要转换: <Fields> <Field> <Name>Element1</Name> <Value>Value 1</Value> </Field> <Field> <Name>Element2</Name> <Value>Value
<Fields>
<Field>
<Name>Element1</Name>
<Value>Value 1</Value>
</Field>
<Field>
<Name>Element2</Name>
<Value>Value 2</Value>
</Field>
</Fields>
要素1
值1
元素2
价值2
进入
值1
价值2
这就是我目前拥有的:
<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>
您的输入XML,
<Fields>
<Field>
<Name>Element1</Name>
<Value>Value 1</Value>
</Field>
<Field>
<Name>Element2</Name>
<Value>Value 2</Value>
</Field>
</Fields>
<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 version="1.0" encoding="UTF-8"?>
<Fields>
<Element1>Value 1</Element1>
<Element2>Value 2</Element2>
</Fields>
要素1
值1
元素2
价值2
通过此XSLT进行转换,
<Fields>
<Field>
<Name>Element1</Name>
<Value>Value 1</Value>
</Field>
<Field>
<Name>Element2</Name>
<Value>Value 2</Value>
</Field>
</Fields>
<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 version="1.0" encoding="UTF-8"?>
<Fields>
<Element1>Value 1</Element1>
<Element2>Value 2</Element2>
</Fields>
生成此输出XML,
<Fields>
<Field>
<Name>Element1</Name>
<Value>Value 1</Value>
</Field>
<Field>
<Name>Element2</Name>
<Value>Value 2</Value>
</Field>
</Fields>
<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 version="1.0" encoding="UTF-8"?>
<Fields>
<Element1>Value 1</Element1>
<Element2>Value 2</Element2>
</Fields>
值1
价值2
根据要求。重要提示:有效的xml元素名称有规则。(1) 名称不得以数字开头。(2) 名称不能以特殊字符(如连字符或句点)开头。(3) 名称不能包含句点、连字符、下划线和冒号以外的特殊字符。可以使用双翻译方法-
,在一定程度上防止无效名称,其中$validChars
是一个变量,包含名称中允许的所有字符。不过这有点粗糙。