XSLT 与 XML 源的默认名称空间设置为 xmlns [英] XSLT with XML source that has a default namespace set to xmlns

查看:19
本文介绍了XSLT 与 XML 源的默认名称空间设置为 xmlns的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文档,其根目录处指示了默认命名空间.像这样的:

I have an XML document with a default namespace indicated at the root. Something like this:

<MyRoot xmlns="http://www.mysite.com">
   <MyChild1>
       <MyData>1234</MyData> 
   </MyChild1> 
</MyRoot>

解析 XML 的 XSLT 无法按预期工作,因为默认命名空间,即当我删除命名空间时,一切都像预计.

The XSLT to parse the XML does not work as expected because of the default namespace, i.e. when I remove the namespace, everything works as expected.

这是我的 XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:template match="/" >
  <soap:Envelope xsl:version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <NewRoot xmlns="http://wherever.com">
       <NewChild>
         <ChildID>ABCD</ChildID>
         <ChildData>
            <xsl:value-of select="/MyRoot/MyChild1/MyData"/>
         </ChildData>
       </NewChild>
     </NewRoot>
   </soap:Body>
  </soap:Envelope>
 </xsl:template>
</xsl:stylesheet>

需要对 XSLT 文档进行哪些操作才能使翻译正常进行?XSLT 文档中究竟需要做什么?

What needs to be done with XSLT document so that translation works properly? What exactly needs to be done in XSLT document?

推荐答案

您需要在 XSLT 中声明命名空间,并在 XPath 表达式中使用它.例如:

You need to declare the namespace in your XSLT, and use it in XPath expressions. E.g.:

<xsl:stylesheet ... xmlns:my="http://www.mysite.com">

   <xsl:template match="/my:MyRoot"> ... </xsl:template>

</xsl:stylesheet>

请注意,如果您想在 XPath 中引用来自该命名空间的元素,您必须提供一些前缀.虽然您可以在没有前缀的情况下执行 xmlns="..." ,并且它适用于文字结果元素,但它不适用于 XPath - 在 XPath 中,始终考虑使用无前缀名称无论范围内的任何 xmlns="..." 为何,都位于具有空白 URI 的命名空间中.

Note that you must provide some prefix if you want to refer to elements from that namespace in XPath. While you can just do xmlns="..." without the prefix, and it will work for literal result elements, it won't work for XPath - in XPath, an unprefixed name is always considered to be in namespace with blank URI, regardless of any xmlns="..." in scope.

这篇关于XSLT 与 XML 源的默认名称空间设置为 xmlns的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆