问题如下,我们需要转换XML文件,客户向我们发送4个不同的文件,每个文件具有不同的名称,每个文件都有唯一的名称空间,但是文档中的元素是相同的。
文件被命名; Supplier_Invoices_1,Supplier_Invoices_2,Supplier_Invoices_3等,没有扩展名,但是它们是XML。
Supplier_Invoices_2的命名空间为:
xmlns:wd="urn:com.cust.report/Supplier_Invoices_2"
对于发票_1:
"urn:com.cust.report/Supplier_Invoices_1"
Invoice_3:
"urn:com.cust.report/Supplier_Invoices_3"
等,等等。
输入-Supplier_Invoices_2示例:
<?xml version='1.0' encoding='UTF-8'?>
<wd:Report_Data xmlns:wd="urn:com.cust.report/Supplier_Invoices_2">
<wd:Report_Entry>
<wd:CF_LRV_Journal_line_group>
<wd:Invoice_Number>SI-00026584</wd:Invoice_Number>
<wd:Supplier_s_Invoice_Number>19031275</wd:Supplier_s_Invoice_Number>
<wd:Invoice_Date>2019-03-18-07:00</wd:Invoice_Date>
<wd:Supplier wd:Descriptor="Company X">
<wd:ID wd:type="WID">d4e89886417501a66aadebf4570da733</wd:ID>
<wd:ID wd:type="Supplier_Reference_ID">SUP924</wd:ID>
<wd:ID wd:type="Supplier_ID">S-00000461</wd:ID>
</wd:Supplier>
<wd:Transaction_Debit_minus_Credit>1956.92</wd:Transaction_Debit_minus_Credit>
</wd:CF_LRV_Journal_line_group>
</wd:Report_Entry>
</wd:Report_Data>
XSLT:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wd="urn:com.cust.report/Supplier_Invoices_2">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xsl:param name="XSLPath" select="base-uri()"/>
<message>
<data>
<xsl:for-each select="/wd:Report_Data/wd:Report_Entry/wd:CF_LRV_Journal_line_group" >
<Documents>
<row>
<path>
<xsl:value-of select="tokenize($XSLPath,'/')[last()]" />
</path>
<CardCode>
<xsl:value-of select="./wd:Supplier/wd:ID[@wd:type='Supplier_ID']"/>
</CardCode>
</row>
</Documents>
<Document_Lines>
<row>
<Price>
<xsl:value-of select="./wd:Transaction_Debit_minus_Credit" />
</Price>
</row>
</Document_Lines>
</xsl:for-each>
</data>
</message>
</xsl:template>
</xsl:stylesheet>
输出:
<?xml version="1.0" encoding="UTF-8"?>
<message xmlns:wd="urn:com.cust.report/Supplier_Invoices_2">
<data>
<Documents>
<row>
<path>Supplier_Invoices_2</path>
<CardCode>S-00000461</CardCode>
</row>
</Documents>
<Document_Lines>
<row>
<Price>1956.92</Price>
</row>
</Document_Lines>
</data>
</message>
我的问题是,如何将XSL文档中的名称空间设置为正在处理的文档的变量?
我在XSL中添加了xsl:param。顶部文档的前5行如下所示:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wd="urn:com.cust.report/$npath" >
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xsl:param name="XSLPath" select="base-uri()"/>
<xsl:param name="npath" select="tokenize($XSLPath,'/')[last()]" />
输出:
<?xml version="1.0" encoding="UTF-8"?>
<message xmlns:wd="urn:com.cust.report/$npath">
<data/>
</message>
任何帮助将不胜感激。
答案 0 :(得分:1)
在XSLT / XPath 2和更高版本中,您可以使用名称空间通配符*:foo
来选择任何名称空间中具有本地名称foo
的元素,因此如果您使用例如用*:Report_Data
代替wd:Report_Data
,您应该能够处理结构相同但名称空间不同的文档。
作为替代方案,您可以在链中使用样式表,在该链中,您可以将不同名称空间中的输入的名称空间标准化为一个公共名称空间,以便随后在第二个样式表中使用该公共名称空间。