【问题标题】:How to treat nodes with xlmns?如何用 xmlns 处理节点?
【发布时间】:2014-06-27 17:56:42
【问题描述】:

我有 XML:

<?xml version="1.0"?>
<arquivoposicao_4_01 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<fundo xmlns="http://tempuri.org/">

我想获取节点&lt;fundo&gt; 的信息,但是我有一些类似上面的xml:&lt;fundo xmlns="http://tempuri.org/"&gt;

当存在这样的命名空间时,我该怎么做&lt;xsl:for-each select="fundo"&gt;

【问题讨论】:

  • 您不要忽略命名空间;你使用它。 --附言请发布一个完整的示例。

标签: xml xslt namespaces xml-namespaces


【解决方案1】:

您需要使用 前缀 声明命名空间,并使用它来限定 XPath 选择器以获取属于该命名空间的元素。您可以通过在您的xsl:stylesheet 中添加一个xmlns 声明来做到这一点,并带有任何前缀:

<xsl:stylesheet version="1.0" 
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:ns1="http://tempuri.org/"> <!-- add this declaration -->

现在您选择 fundo 以使用您声明的前缀限定选择器。在本例中,您将使用ns1:fundo

<xsl:for-each select="ns1:fundo">
    ...

【讨论】:

    【解决方案2】:

    你有几个选择:

    选项 1

    声明命名空间(将xmlns:t="http://tempuri.org/" 添加到xsl:stylesheet)并在您的xpath 中使用它(“t”前缀可以是任何东西):

    <xsl:for-each select="t:fundo"></xsl:for-each>
    

    选项 2

    在 xpath 中使用local-name()

    <xsl:for-each select="*[local-name()='fundo']"></xsl:for-each>
    

    您也可以使用namespace-uri() 来确保您选择的正是您想要的:

    <xsl:for-each select="*[local-name()='fundo' and namespace-uri()='http://tempuri.org/']"></xsl:for-each>
    

    选项 3(仅限 XSLT 2.0)

    使用* 作为前缀:

    <xsl:for-each select="*:fundo"></xsl:for-each>
    

    这可以与选项 2 中的namespace-uri() 结合使用。

    选项 4(仅限 XSLT 2.0)

    xpath-default-namespace 属性添加到xsl:stylesheet

     xpath-default-namespace="http://tempuri.org/"
    

    【讨论】:

      【解决方案3】:

      如果你有这样的 XML:

      <fundo xmlns="http://tempuri.org/">
      

      <t:fundo xmlns:t="http://tempuri.org/">
      

      元素名称fundo 可以读作{http://tempuri.org/}:fundo。该元素位于特定的命名空间中。所以忽略它不是一个好主意,它会改变语义。

      Xpath 也为命名空间使用别名。所以你必须在 XSL 样式表元素上定义命名空间:

      <xsl:stylesheet version="1.0" 
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:temp="http://tempuri.org/">
      

      该定义独立于源 XML 中的定义。您现在可以使用别名/前缀temp 访问命名空间http://tempuri.org/ 中的元素fundo

      <xsl:for-each select="temp:fundo">
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 2018-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        相关资源
        最近更新 更多