【问题标题】:Extract xml element and child node values提取 xml 元素和子节点值
【发布时间】:2013-04-25 00:47:19
【问题描述】:

我有一个以下类型的 xml

`<ns:response>
 <ns:transport_car>
  <ns:transport_model> abc</ns:transport_model>
  <ns:transport_model> xyz</ns:transport_model>
   </ns:transport_car>
    </ns:response>`

我如何格式化这个 xsl 以打印表单文本:

Transport type= car
Model name:
abc xyz

【问题讨论】:

    标签: xslt xml-parsing


    【解决方案1】:

    这种转变

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:ns="some:ns">
     <xsl:output method="text"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:template match="/*/*[starts-with(local-name(), 'transport_')]">
      <xsl:text>Transport type= </xsl:text>
      <xsl:value-of select="substring-after(local-name(), 'transport_')"/>
      <xsl:apply-templates/>
     </xsl:template>
    
     <xsl:template match="ns:transport_model[1]">
    Model name:
    <xsl:value-of select="normalize-space()"/>
     </xsl:template>
    </xsl:stylesheet>
    

    应用于提供的 XML 文档时:

    <ns:response xmlns:ns="some:ns">
        <ns:transport_car>
            <ns:transport_model> abc</ns:transport_model>
            <ns:transport_model> xyz</ns:transport_model>
        </ns:transport_car>
    </ns:response>
    

    产生想要的正确结果:

    Transport type= car
    Model name:
    abc xyz
    

    【讨论】:

      【解决方案2】:

      这是怎么回事:

      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                      xmlns:ns="something">
        <xsl:output method="text" indent="yes"/>
      
        <xsl:template match="/*">
          <xsl:apply-templates
            select="*[substring-after(local-name(), 'transport_') != '']" />
        </xsl:template>
      
        <xsl:template match="/*/*">
          <xsl:value-of
            select="concat('Transport type= ', 
                           substring-after(local-name(), 'transport_'),
                           '&#xA;Model name:&#xA;')"/>
          <xsl:apply-templates select="ns:transport_model" />
        </xsl:template>
      
        <xsl:template match="ns:transport_model">
          <xsl:value-of select="concat(normalize-space(), ' ')"/>
        </xsl:template>
      </xsl:stylesheet>
      

      在示例输入上运行时(添加命名空间后),结果为:

      Transport type= car
      Model name:
      abc xyz 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 2013-09-06
        • 1970-01-01
        相关资源
        最近更新 更多