首页 > 解决方案 > 如何将 xml 的一部分转换为没有命名空间的新 xml?

问题描述

我在将部分 xml 转换为没有命名空间的新 xml 时遇到了麻烦。输入xml是:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<node1 xmlns="http://a.com">
    <ServiceData>
        <b:test xmlns:b="http://b.com">
            <b:somtag>
            </b:somtag>
        </b:test>
    </ServiceData>
</node1>

我想要的是:

<a>
    <c>
        <ServiceData>
            <b:test xmlns:b="http://b.com">
                <b:somtag>
                </b:somtag>
            </b:test>
        </ServiceData>
    </c>
</a>

我想要的格式是没有 ServiceData 的命名空间。任何帮助表示赞赏,谢谢。

补充,我尝试使用这个 xsl,但我无法删除 "xmlns="http://a.com""

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:test="http://a.com" exclude-result-prefixes="test">

    <xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes" />

    <xsl:template match="/">
        <a><c><ServiceData><xsl:copy-of select="//test:ServiceData/*"/></ServiceData></c></a>
    </xsl:template>

</xsl:stylesheet>

我得到的结果是:

<a>
    <c>
        <ServiceData>
            <b:test xmlns:b="http://b.com" xmlns="http://a.com">
            <b:somtag>
            </b:somtag>
        </b:test>
        </ServiceData>
    </c>
</a>

标签: xslt

解决方案


怎么样:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xpath-default-namespace="http://a.com">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />

<xsl:template match="/node1">
    <a>
        <c>
            <ServiceData>
                <xsl:copy-of select="ServiceData/*" copy-namespaces="no" />
            </ServiceData>
        </c>
    </a>
</xsl:template>

</xsl:stylesheet>

添加:

我假设您可以使用 XSLT 2.0 处理器,因为您的样式表显示version="2.0". 如果那不是真的,那么你不能使用xsl:copy-of; 相反,您必须使用其原始名称和命名空间重构元素:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:test="http://a.com" 
exclude-result-prefixes="test">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/test:node1">
    <a>
        <c>
            <ServiceData>
                <xsl:apply-templates select="test:ServiceData/*"/>
            </ServiceData>
        </c>
    </a>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{name()}" namespace="{namespace-uri()}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

笔记:

多余的命名空间声明不应对接收应用程序产生任何影响。此处收到的结果在语义上与您在问题中显示的结果相同。


推荐阅读