用于删除命名空间的 XSLT 映射


  1. 我对XSLT映射很陌生,但卡住了。我了解某些功能的使用。 请建议一些教程通读。
  2. 我在下面输入代码:

    <?xml version="1.0" encoding="utf-8"?>
    <ns0:hr xmlns:ns0="Namesapace.com">
    <Resources>
    <EmployeesRecords>
    <Record RecordId="1">
    <Name>AAA € </Name>
    <ID>111</ID>
    <Phone>1111111111</Phone>
    </Record>
    <Record RecordId="2">
    <Name>BBB</Name>
    <ID>222</ID>
    <Phone>2222222222</Phone>
    </Record>
    </EmployeesRecords>
    <ContractorsRecords>
    <Record RecordId="3">
    <Name>ZZZ</Name>
    <ID>999</ID>
    <Phone>9999999999</Phone>
    </Record>
    </ContractorsRecords>
    </Resources>
    </ns0:hr>
    

我期待下面这样的事情,

<?xml version="1.0" encoding="utf-8"?>
<Resources>
<EmployeesRecords>
<Record RecordId="1">
<Name>AAA € </Name>
<ID>111</ID>
<Phone>1111111111</Phone>
</Record>
<Record RecordId="2">
<Name>BBB</Name>
<ID>222</ID>
<Phone>2222222222</Phone>
</Record>
</EmployeesRecords>
<ContractorsRecords>
<Record RecordId="3">
<Name>ZZZ</Name>
<ID>999</ID>
<Phone>9999999999</Phone>
</Record>
</ContractorsRecords>
</Resources>

请指教。

从您的问题中不清楚您要做什么,但是给定问题标题,以下 XSLT 应该删除所有命名空间....

但请注意,命名空间是 XML 元素/属性名称的一部分,因此删除它们会从根本上更改 XML 文档。

<?xml version="1.0"?>
<!-- Created with Liquid Studio 2017 (https://www.liquid-technologies.com) -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="yes"/>
<!-- Stylesheet to remove all namespaces from a document -->
<!-- NOTE: this will lead to attribute name clash, if an element contains
two attributes with same local name but different namespace prefix -->
<!-- Nodes that cannot have a namespace are copied as such -->
<!-- template to copy elements -->
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@* | node()"/>
</xsl:element>
</xsl:template>
<!-- template to copy attributes -->
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<!-- template to copy the rest of the nodes -->
<xsl:template match="comment() | text() | processing-instruction()">
<xsl:copy/>
</xsl:template>
</xsl:stylesheet>

通过查看输入和输出不清楚实际的转换规则是什么。例如,您如何确定第一条记录应该具有

<Name>AAA € </Name>
<ID>111</ID>

而不是

<Name>AAA</Name>
<ID>€ 111</ID>

确定规则后,使用 xsl:analyze-string 指令在 XSLT 2.0 中实现它们应该很简单。在 XSLT 1.0(许多人尽管已经 18 岁了,但仍在使用(中,它可能要困难得多。

至于你对教程的要求,我只能推荐我的书:来自Wiley/Wrox的XPath 2.0和XSLT 2.0 Programmer's Reference,第4版。