Arrays XSL-将数组元素转换为元素名+索引名的独立元素列表
我对XSL转换有非常基本的了解。 我需要将数组转换为独立元素列表,如下所示: 输入:Arrays XSL-将数组元素转换为元素名+索引名的独立元素列表,arrays,xml,xslt,transformation,Arrays,Xml,Xslt,Transformation,我对XSL转换有非常基本的了解。 我需要将数组转换为独立元素列表,如下所示: 输入: <Fields> <Field> <Name>One</Name> <Value>1</Value> </Field> <Field> <Name>Two</Name> <Value>2&l
<Fields>
<Field>
<Name>One</Name>
<Value>1</Value>
</Field>
<Field>
<Name>Two</Name>
<Value>2</Value>
</Field>
<Field>
<Name>Three</Name>
<Value>3</Value>
</Field>
<Field>
<Name>Four</Name>
<Value>4</Value>
</Field>
</Fields>
期望输出:
<Fields>
<Field1>
<Name>One</Name>
<Value>1</Value>
</Field1>
<Field2>
<Name>Two</Name>
<Value>2</Value>
</Field2>
<Field3>
<Name>Three</Name>
<Value>3</Value>
</Field3>
<Field4>
<Name>Four</Name>
<Value>4</Value>
</Field4>
</Fields>
这完全可行吗?
谢谢你的建议
这个问题背后的真正原因是消费者的软件
如果字段名称不由静态xml表示,则无法映射字段
节点
我不确定这到底意味着什么,但如果您确定这是您想要的结果,请尝试:
<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:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Field">
<xsl:element name="Field{position()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
来自michael.hor257k的答案非常有效,完全回答了我最初的问题,但我意识到,如果字段名是唯一的,那么这个转换的输出更适合我的需要
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/*">
<Fields>
<xsl:apply-templates select="Field" />
</Fields>
</xsl:template>
<xsl:template match="Field">
<xsl:element name="{Name}">
<xsl:element name="Value">
<xsl:value-of select="Value" />
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
输出:
<?xml version="1.0"?>
<Fields>
<One>
<Value>1</Value>
</One>
<Two>
<Value>2</Value>
</Two>
<Three>
<Value>3</Value>
</Three>
<Four>
<Value>4</Value>
</Four>
</Fields>
可行,对。然而,在去那里之前,你应该三思而后行,因为虽然改变并没有带来我所能看到的优势,但它会使结果比原来的结果更难处理。-还要注意,您的输出缺少每个XML文档都必须具有的根元素。该输出不是有效的XML,因为它有多个根元素。此外,您的XML中的元素是否实际被称为字段,或者您是否正在寻找更通用的解决方案?很抱歉,缺少根元素,请确保它应该具有一个。它不是生产xml,只是一个说明问题的人工示例。这个问题背后的真正原因是,如果字段的名称不由静态xml节点表示,则消费者的软件无法映射字段。太棒了!工作起来很有魅力。我还发现了另一个类似的解决方案-。它将元素转换为相应的{Name}元素。接受了我的问题,并把它作为一个答案。