如何用XSLT 2.0(Saxon解析器)美化输出内嵌XML
解决方案:使用
parse-xml()解析内嵌XML字符串并格式化 你可以借助XSLT 2.0的parse-xml()标准函数,直接将转义的XML字符串解析为完整的节点树,而非仅仅输出未转义的文本。这样Saxon就能识别XML结构,自动应用indent="yes"的输出规则,一次性完成提取与美化排版。
以下是适配你的需求的完整XSLT代码:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="utf-8"/> <xsl:template match="/"> <!-- 将转义XML字符串解析为节点树,再复制输出触发格式化 --> <xsl:copy-of select="parse-xml(/Container/Object/Metadata/Fields/Field[@Label='Contents']/Value)"/> </xsl:template> </xsl:stylesheet>
原理说明
- 你之前使用
xsl:value-of disable-output-escaping="yes"的方式,本质是把转义字符还原后输出纯文本内容,处理器不会将其当作XML节点处理,因此无法触发缩进格式化。 parse-xml()函数会将字符串形式的XML解析成标准XML节点树,后续用xsl:copy-of输出时,Saxon会严格遵循xsl:output中的indent="yes"配置,自动生成整齐美观的XML结构。
注意事项
- 确保内嵌的XML字符串格式完全合规(你的示例内容符合要求),
parse-xml()才能正常完成解析。 - 该方案完全适配Saxon,因为
parse-xml()是XSLT 2.0的内置标准函数,Saxon对其支持完善。
执行后你会得到如下格式化后的XML结果:
<?xml version="1.0" encoding="utf-8"?> <Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:qdt="urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2" xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns:cur="urn:oasis:names:tc:ubl:codelist:CurrencyCode:1:0" xmlns:sdt="urn:oasis:names:tc:ubl:SpecializedDatatypes:1:0" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:udt="urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <cbc:UBLVersionID xmlns="">2.1</cbc:UBLVersionID> <cbc:CustomizationID xmlns="">urn:www.cenbii.eu:transaction:biitrns010:ver2.0:extended:urn:www.peppol.eu:bis:peppol4a:ver2.0:extended:urn:www.difi.no:ehf:faktura:ver2.0</cbc:CustomizationID> <cbc:ProfileID xmlns="">urn:www.cenbii.eu:profile:bii04:ver2.0</cbc:ProfileID> <cbc:ID xmlns="">821576</cbc:ID> <cbc:IssueDate xmlns="">2018-04-30</cbc:IssueDate> <cbc:InvoiceTypeCode xmlns="" listAgencyID="6" listID="UNCL1001">380</cbc:InvoiceTypeCode> <cbc:TaxPointDate xmlns="">2018-04-30</cbc:TaxPointDate> <cbc:DocumentCurrencyCode xmlns="" listAgencyID="6" listID="ISO4217">NOK</cbc:DocumentCurrencyCode> <cbc:AccountingCost xmlns="">2007</cbc:AccountingCost> <cac:ContractDocumentReference xmlns=""> <cbc:ID>2007</cbc:ID> </cac:ContractDocumentReference> </Invoice>
内容的提问来源于stack exchange,提问作者bjornno
相关产品推荐
相关产品推荐

