XSLT转换优化:新增移除特定下划线前缀标签的需求
调整XSLT转换代码以新增标签移除规则
初始XML文件
<root> <_D>urn:oasis:names:specification:ubl:schema:xsd:Invoice-2</_D> <_A>urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2</_A> <_B>urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2</_B> <Invoice> <ID> <_>INV12345</_> </ID> <InvoiceTypeCode> <_>01</_> <listVersionID>1.0</listVersionID> </InvoiceTypeCode> <InvoicePeriod> <StartDate> <_>2017-11-26</_> </StartDate> <EndDate> <_>2017-11-30</_> </EndDate> </InvoicePeriod> <AccountingSupplierParty> <AdditionalAccountID> <_>id-1234</_> <schemeAgencyName>name1</schemeAgencyName> </AdditionalAccountID> </AccountingSupplierParty> </Invoice> </root>
转换后目标XML文件
<Invoice> <ID>INV12345</ID> <InvoiceTypeCode listVersionID="1.0">01</InvoiceTypeCode> <InvoicePeriod> <StartDate>2017-11-26</StartDate> <EndDate>2017-11-30</EndDate> </InvoicePeriod> <AccountingSupplierParty> <AdditionalAccountID schemeAgencyName="name1">id-1234</AdditionalAccountID> </AccountingSupplierParty> </Invoice>
转换要求
- 移除所有以“_”开头且标签名长度大于1的标签(如<_D>、<_A>、<_B>)
- 移除root标签
- 移除所有<_>标签,并将其内容移至父标签中
- 将所有非<_>的子标签转换为父标签的属性
修改后的XSLT代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <!-- 转换非<_>的叶子子元素为属性,排除待移除的下划线开头长标签 --> <xsl:for-each select="*[not(* or self::_ or starts-with(name(), '_') and string-length(name()) > 1)]"> <xsl:attribute name="{name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:for-each> <!-- 处理其他子元素和文本节点,跳过待移除的下划线开头长标签 --> <xsl:apply-templates select="*[*] | _ | text() | *[not(starts-with(name(), '_') and string-length(name()) > 1)]"/> </xsl:copy> </xsl:template> <!-- 移除root、<_>以及以_开头且长度大于1的标签 --> <xsl:template match="/* | _ | *[starts-with(name(), '_') and string-length(name()) > 1]"> <xsl:apply-templates/> </xsl:template> </xsl:stylesheet>
修改说明
- 在移除标签的匹配模板中,新增了
*[starts-with(name(), '_') and string-length(name()) > 1]规则,直接匹配并移除符合条件的标签; - 调整了通用模板中转换属性的选择器,排除了需要移除的下划线开头长标签;
- 更新了
apply-templates的选择范围,确保不会处理这些待移除的标签。
内容的提问来源于stack exchange,提问作者Volodymyr Patriiuk
相关产品推荐
相关产品推荐

