【问题标题】:After adding namespace cannot get required output xml添加命名空间后无法获得所需的输出xml
【发布时间】:2013-05-06 17:58:59
【问题描述】:

如果我将命名空间 xmlns="http://www.yahoo.com/xmlns/ApplicationTest" 添加为

<?xml version="1.0" xmlns="http://www.yahoo.com/xmlns/ApplicationTest" encoding="UTF-8"?>

在我的帖子中的 usa11.xml 和 usa22.xml 中:

Updating info in one XML file with optional info from another, using XSLT

看起来 xslt 无法输出预期结果; 没有这个 xmlns="http://www.yahoo.com/xmlns/ApplicationTest"

请帮助如何使用 XSL 修复它??

谢谢'

【问题讨论】:

  • 也许你应该开始决定你之前问题的哪些答案是有效的,或者说为什么没有。
  • XML 声明中的 xmlns 属性?你是从哪里得到这个想法的?

标签: xml xslt


【解决方案1】:

如果您需要引用 XML 数据中名称属于某个名称空间的任何元素,您必须在样式表中为该名称空间分配一个 前缀。在样式表中,XSLT 认为 XPath 表达式或匹配模式中名称不带前缀的每个元素都没有命名空间,即使有默认的xmlns="http://..." 定义。

所以你必须写类似的东西

xmlns:app="http://www.yahoo.com/xmlns/ApplicationTest"

然后在目标 XML 数据中的所有节点引用前加上新的命名空间,例如 app:root

如果没有看到您的实时数据,我无法举出更好的例子。我希望这很清楚。

【讨论】:

    【解决方案2】:

    要使以前的 answer 中的样式表正常工作,请将命名空间声明添加到样式表(带有前缀)并为所有节点名称使用新的命名空间前缀。

    因此应该这样做:

    <?xml version="1.0" encoding="utf-8"?>
    
    <xsl:stylesheet version="1.0"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:y="http://www.yahoo.com/xmlns/ApplicationTest"
                    >
    
        <xsl:variable name="u2" select="document('usaa22.xml')"/>
        <xsl:template match="y:city">
            <xsl:choose>
                <xsl:when test="$u2//y:city[y:street=current()/y:street]">
                    <xsl:copy>
                        <xsl:apply-templates select="$u2//y:city[y:street=current()/y:street]/* " />
                    </xsl:copy>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:copy>
                        <xsl:apply-templates select="@* | node() " />
                    </xsl:copy>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:template>
    
        <xsl:template match="node() | @*">
            <xsl:copy>
                <xsl:apply-templates select="@* | node() " />
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    

    注意:您的 xml 更改似乎不正确:

    <?xml version="1.0" xmlns="http://www.yahoo.com/xmlns/ApplicationTest" encoding="UTF-8"?>
    

    &lt;?xml 序言不允许命名空间。
    命名空间应添加到 xml 文件中的第一个元素:

    <country xmlns="http://www.yahoo.com/xmlns/ApplicationTest">
    

    【讨论】:

    • @LarsH:非常感谢你修复和纠正了我糟糕的英语。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    相关资源
    最近更新 更多