【发布时间】:2014-06-10 16:07:30
【问题描述】:
我有来自供应商的这个源 XML:
源 XML
<?xml version="1.0" encoding="UTF-8"?>
<src:view name="books"
xmlns="xyz.com/wow"
xmlns:src="xyz.com/fun"
xmlns:xsi="w3.org/2001/XMLSchema-instance">
<books>
<title>Searching for Answers</title>
</books>
<books>
<title>Get Rich Quick</title>
</books>
<books>
<title>Negotiating with the Grim Reaper</title>
</books>
</src:view>
我想转换成一个带有根元素books 的新文档,然后复制所有books 元素,但将名称从books 更改为books_record。文档将是任意的(books 今天,widgets 明天,等等),但根的孩子的元素名称始终可以从 /@name 获得,这是供应商约定。
预期输出
<books>
<books_record>
<title>Searching for Answers</title>
</books_record>
<books_record>
<title>Get Rich Quick</title>
</books_record>
<books_record>
<title>Negotiating with the Grim Reaper</title>
</books_record>
</books>
我管理了正确的根元素和所有子元素的复制,但我不确定如何将所有 <books> 更改为 <books_record>。另外,到目前为止,我所拥有的是否有效且有效?我知道它有效,只是不能 100% 确定它是否是最好的方法。
到目前为止的 XSL(在 michael.hor257k 的帮助下更新)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
exclude-result-prefixes="xsl" version="2.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8"
indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:copy-of select="@*" />
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="/*">
<xsl:variable name="rootElementName">
<xsl:value-of select="@name" />
</xsl:variable>
<xsl:element name="{$rootElementName}">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
<xsl:template match="/*/node()">
<xsl:variable name="rootElementName">
<xsl:value-of select="/*/@name" />
</xsl:variable>
<xsl:element name="{$rootElementName}_record">
<xsl:apply-templates />
</xsl:element>
</xsl:template>
</xsl:transform>
【问题讨论】: