我在XML文件中插入schemaLocation时遇到问题。我几乎得到了预期的输出,但其他元素填充了schemaLocation。这是我的示例文件:
INPUT:
<Sync releaseID="9.2">
<Document>
<Group>
<Header>
<Field1>232</Field1>
<Field2>dfd</Field2>
</Header>
</Group>
</Document>
而且,我想在<Document>
标记中添加名称空间和schemalocation。这是我的XSLT:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor-or-self::Document]">
<xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<xsl:attribute name="xsi:schemaLocation">urn:iso:std:iso:20022:tech:xsd:pain.001.001.03</xsl:attribute>
<xsl:apply-templates select="*"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
生成的输出:
<Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<Group xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<Header xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<Field1 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">232</Field1>
<Field2 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">dfd</Field2>
</Header>
</Group>
</Document>
预期输出
<Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<Group>
<Header>
<Field1>232</Field1>
<Field2>dfd</Field2>
</Header>
</Group>
</Document>
如何删除其他元素中的schemaLocation?
感谢。
答案 0 :(得分:1)
您只想对Document
元素执行此特殊处理,而不是对作为祖先Document
的每个元素执行此处理,因此只需将匹配模式从match="*[ancestor-or-self::Document]"
更改为{{ 1}}。
答案 1 :(得分:0)
您需要添加仅匹配Document
的模板,并在那里添加属性(仅在那里)。然后更改现有模板,使其仅匹配Document
的后代:
<xsl:stylesheet version="2.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="*[ancestor::Document]">
<xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<xsl:apply-templates select="*"/>
</xsl:element>
</xsl:template>
<xsl:template match="Document">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<xsl:apply-templates select="*"/>
</Document>
</xsl:template>
</xsl:stylesheet>