【问题标题】:XSL namespaces and nested xsl:for-eachXSL 命名空间和嵌套的 xsl:for-each
【发布时间】:2011-06-06 10:49:11
【问题描述】:

我有以下 XML 并希望遍历元素,因此我可以以某种格式显示它,例如:

PIN 1<br/>
&nbsp;&nbsp;  XYZ<br/>
&nbsp;&nbsp;  HELLO<br/>

PIN 2<br/>
&nbsp;&nbsp;  ABC<br/>
&nbsp;&nbsp;  HI<br/>

XML:

<RootResponse xmlns:ip="urn:domain:tx:inPayment" xmlns:ipn="urn:domain:tx:Pin">
   <OutBoundMessage>
      <ip:InfoMessage>
        <ipn:Alert>PIN 1</ipn:Alert>
         <ipn:Code>
           <ip:CodeLabel>XYZ</ip:CodeLabel>
           <ip:CodeMessage>HELLO</ip:CodeMessage>
         </ipn:Code>
      </ip:InfoMessage>

      <ip:InfoMessage>
         <ipn:Code>
           <ipn:Alert>PIN 2</ipn:Alert>
           <ip:CodeLabel>ABC</ip:CodeLabel>
           <ip:CodeMessage>HI</ip:CodeMessage>
         </ipn:Code>
      </ip:InfoMessage>
  </OutBoundMessage>
</RootResponse>

我似乎找不到解决方案。有什么建议吗?

【问题讨论】:

    标签: xslt


    【解决方案1】:

    我建议关注W3C schools XSLT tutorial,这应该可以为您提供解决这个相对简单的 XSLT 问题所需的一切。

    您是对的,您必须注意命名空间,尽管这同样非常简单。只需确保您的 XSLT 定义了所需的名称空间,并相应地在 XPath 语句中为元素名称添加前缀。请参阅以下内容:

    XML Namespaces and How They Affect XPath and XSLT

    【讨论】:

      【解决方案2】:

      您应该在 XSLT 中声明命名空间,然后在表达式中使用声明的前缀。

      下面是如何做到这一点的示例,使用模板(即“推式”)而不是xsl:for-each(例如“拉式”)。

      <?xml version="1.0"?>
      <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:ip="urn:domain:tx:inPayment"
      xmlns:ipn="urn:domain:tx:Pin"
      exclude-result-prefixes="ip ipn">
          <xsl:output indent="yes" />
      
          <xsl:template match="ipn:Alert">
              <xsl:text>&#xA;</xsl:text>
              <xsl:apply-templates />
              <br/>
          </xsl:template>
      
          <xsl:template match="ip:*[starts-with(local-name(),'Code')]">
              <xsl:text>&#xA;&#160;&#160;</xsl:text>
              <xsl:apply-templates/>
              <br/>
          </xsl:template>
      
      </xsl:stylesheet>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 2014-12-01
        • 1970-01-01
        • 2011-01-06
        相关资源
        最近更新 更多