我想删除 xml 文件中元素值内不必要的文本,并且我想使用 XSLT 转换来做到这一点。
在此示例文件中,我想删除
<br>
、<preffix>
、<suffix>
元素内部值中的特定标签。会有很多<Value>
元素。我不想更改此文件的结构,因此这应该类似于副本,但具有删除特定文本的逻辑。
我尝试使用模板和复制,但不知何故我无法将它们连接在一起。如果你们中的任何人可以帮助我或给我应该遵循的提示,我将不胜感激。
<Product>
输出文件应如下所示:
<ProductInfo>
<Products>
<Product>
<Name>xyz</Name>
<Values>
<Value><br/>test</Value> <-- remove <br/>
<Value><preffix/>test2</Value> <-- remove <preffix>
<Value><suffix/>test3</Value> <-- remove <suffix/>
</Values>
</Product>
<Product>
<Name>xyz</Name>
<Values>
<Value><br/>test</Value> <-- remove <br/>
<Value><preffix/>test2</Value> <-- remove <preffix>
<Value><suffix/>test3</Value> <-- remove <suffix/>
</Values>
</Product>
</Products>
</ProductInfo>
<ProductInfo>
<Products>
<Product>
<Name>xyz</Name>
<Values>
<Value>test</Value>
<Value>test2</Value>
<Value>test3</Value>
</Values>
</Product>
<Product>
<Name>xyz</Name>
<Values>
<Value>test</Value>
<Value>test2</Value>
<Value>test3</Value>
</Values>
</Product>
</Products>
</ProductInfo>
将通过仅返回
<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="Value">
<xsl:copy>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
元素中包含的任何标记
字符串值- 即“按文档顺序排列元素节点的所有文本节点后代的字符串值的串联”。
以及与您要删除/删除的内容相匹配的附加空模板来完成此操作。
Value
您可以为每个匹配模式使用单独的空匹配模板,而不是使用
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!--empty template matching the elements that we want to drop and not appear in the result-->
<xsl:template match="Value/br | Value/prefix | Value|suffix"/>
</xsl:stylesheet>
联合。
此外,如果您想删除出现在|
元素内部的所有元素,您可以使用
Value
进行更通用的匹配。