我有一个以下格式的输入 XML:
<Plugins>
<AssemblyName>msoft, Version=5.0, Culture=neutral, PublicKeyToken=null</AssemblyName>
<TypeName>BT</TypeName>
<Version>?</Version>
<Configuration><AppData xmlns="http://tempuri.org/AppData.xsd">
<Readers>
<Id>1234</Id>
<Port>6500</Port>
<Type>M200</Type>
<Active>Yes</Active>
</Readers>
<Readers>
...
</Configuration>
...
</Plugins>
我想将其转换为另一种 XML,如下所示,
<Plugins>
<MyReaders>
<DeviceId>1234</DeviceId>
<PortNum>6500</PortNum>
<ModelType>M200</ModelType>
<Active>Yes</Active>
</MyReaders>
</Plugins>
我想使用 XSLT 进行转换。我怎样才能做到这一点?
我将使用您提供的示例,并假设它格式良好。为此,我在源代码中添加了四行,现在是:
<Plugins>
<AssemblyName>msoft, Version=5.0, Culture=neutral, PublicKeyToken=null</AssemblyName>
<TypeName>BT</TypeName>
<Version>?</Version>
<Configuration>
<AppData xmlns="http://tempuri.org/AppData.xsd">
<Readers>
<Id>1234</Id>
<Port>6500</Port>
<Type>M200</Type>
<Active>Yes</Active>
</Readers>
<Readers>
</Readers>
</AppData>
</Configuration>
</Plugins>
您将需要 XSLT 2.0 处理器或 XSLT 1.0 扩展。这是使用 XSLT 2.0 的解决方案:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tempuri="http://tempuri.org/AppData.xsd"
exclude-result-prefixes="tempuri"
version="2.0">
<xsl:output method="xml" indent="yes" use-character-maps="angle-brackets"/>
<xsl:character-map name="angle-brackets">
<xsl:output-character character="<" string="<"/>
<xsl:output-character character=">" string=">"/>
</xsl:character-map>
<xsl:strip-space elements="*"/>
<xsl:template match="Plugins">
<xsl:copy>
<xsl:apply-templates select="Configuration"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Configuration">
<xsl:variable name="input">
<xsl:value-of select="."/>
</xsl:variable>
<xsl:apply-templates select="document(concat('data:text/xml,',$input))/tempuri:AppData/tempuri:Readers" />
</xsl:template>
<xsl:template match="tempuri:Readers">
<MyReaders>
<DeviceId><xsl:value-of select="tempuri:Id"/></DeviceId>
<PortNum><xsl:value-of select="tempuri:Port"/></PortNum>
<ModelType><xsl:value-of select="tempuri:Type"/></ModelType>
<Active><xsl:value-of select="tempuri:Active"/></Active>
</MyReaders>
</xsl:template>
</xsl:stylesheet>
它实际上会处理您的数据两次。内容内的尖括号Configuration
使用转换character-map
。结果被放置在变量中$input
使用以下方法将其转换为节点document()
功能。
由于您的数据位于命名空间中,因此有必要在 XPath 表达式前面加上它的前缀。使用以下命令从结果中删除名称空间声明exclude-result-prefixes="tempuri"
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)