XSLT (Extensible Stylesheet Language Transformations) 是一种用于转换XML文档的语言,它可以将XML文档转换为其他格式(如HTML、XML或纯文本)。在这个问题中,我们需要使用XSLT来修改XML文档,为某些值添加标记并作为ID属性。
假设我们有以下输入XML:
<root>
<item>Apple</item>
<item>Banana</item>
<item>Orange</item>
</root>
我们想要将每个<item>
元素转换为带有ID属性的新元素,ID值就是元素的内容。以下是实现这一目标的XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="root"/>
</xsl:template>
<xsl:template match="root">
<root>
<xsl:apply-templates select="item"/>
</root>
</xsl:template>
<xsl:template match="item">
<newItem id="{.}">
<xsl:value-of select="."/>
</newItem>
</xsl:template>
</xsl:stylesheet>
转换后的输出将是:
<root>
<newItem id="Apple">Apple</newItem>
<newItem id="Banana">Banana</newItem>
<newItem id="Orange">Orange</newItem>
</root>
如果原始XML更复杂,例如:
<products>
<product>
<name>Laptop</name>
<price>999</price>
</product>
<product>
<name>Phone</name>
<price>699</price>
</product>
</products>
我们想为每个<product>
添加一个ID属性,值为<name>
的内容:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="products"/>
</xsl:template>
<xsl:template match="products">
<products>
<xsl:apply-templates select="product"/>
</products>
</xsl:template>
<xsl:template match="product">
<product id="{name}">
<xsl:copy-of select="*"/>
</product>
</xsl:template>
</xsl:stylesheet>
输出将是:
<products>
<product id="Laptop">
<name>Laptop</name>
<price>999</price>
</product>
<product id="Phone">
<name>Phone</name>
<price>699</price>
</product>
</products>
{...}
语法可以直接将表达式结果作为属性值问题1:ID值包含非法字符(如空格)
translate()
或normalize-space()
<product id="{translate(name, ' ', '_')}">
问题2:需要生成唯一ID而非直接使用值
generate-id()
函数<product id="{generate-id()}">
问题3:需要保留原始元素结构
xsl:copy
和xsl:attribute
组合<xsl:template match="product">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="name"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
这种技术常用于:
通过XSLT的这种转换能力,可以灵活地处理XML数据,满足各种系统集成和数据交换的需求。
没有搜到相关的文章