一个 XMl 文档可以有两个不同的元素,分别命名为:MyName 和 myName——它们是不同的。将它们转换/视为同名是一个错误,可能会产生严重后果。
如果不是上述情况,那么这里有一个更精确的解决方案,使用 XSLT 将文档处理成只有小写元素名称和小写属性名称的文档:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vUpper" select=
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="vLower" select=
"'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[name()=local-name()]" priority="2">
<xsl:element name="{translate(name(), $vUpper, $vLower)}"
namespace="{namespace-uri()}">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
<xsl:template match="*" priority="1">
<xsl:element name=
"{substring-before(name(), ':')}:{translate(local-name(), $vUpper, $vLower)}"
namespace="{namespace-uri()}">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*[name()=local-name()]" priority="2">
<xsl:attribute name="{translate(name(), $vUpper, $vLower)}"
namespace="{namespace-uri()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<xsl:template match="@*" priority="1">
<xsl:attribute name=
"{substring-before(name(), ':')}:{translate(local-name(), $vUpper, $vLower)}"
namespace="{namespace-uri()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
当此转换应用于任何 XML 文档时,例如这个:
<authors xmlns:user="myNamespace">
<?ttt This is a PI ?>
<Author xmlns:user2="myNamespace2">
<Name idd="VH">Victor Hugo</Name>
<user2:Name idd="VH">Victor Hugo</user2:Name>
<Nationality xmlns:user3="myNamespace3">French</Nationality>
</Author>
<!-- This is a very long comment the purpose is
to test the default stylesheet for long comments-->
<Author Period="classical">
<Name>Sophocles</Name>
<Nationality>Greek</Nationality>
</Author>
<author>
<Name>Leo Tolstoy</Name>
<Nationality>Russian</Nationality>
</author>
<Author>
<Name>Alexander Pushkin</Name>
<Nationality>Russian</Nationality>
</Author>
<Author Period="classical">
<Name>Plato</Name>
<Nationality>Greek</Nationality>
</Author>
</authors>
生成所需的正确结果(元素和属性名称转换为小写):
<authors><?ttt This is a PI ?>
<author>
<name idd="VH">Victor Hugo</name>
<user2:name xmlns:user2="myNamespace2" idd="VH">Victor Hugo</user2:name>
<nationality>French</nationality>
</author><!-- This is a very long comment the purpose is
to test the default stylesheet for long comments-->
<author period="classical">
<name>Sophocles</name>
<nationality>Greek</nationality>
</author>
<author>
<name>Leo Tolstoy</name>
<nationality>Russian</nationality>
</author>
<author>
<name>Alexander Pushkin</name>
<nationality>Russian</nationality>
</author>
<author period="classical">
<name>Plato</name>
<nationality>Greek</nationality>
</author>
</authors>
一旦将文档转换为所需的形式,您就可以对转换后的文档执行任何所需的处理。