提取XML元素和子节点值

问题描述:

我有以下类型提取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的XML打印格式的文本:

Transport type= car 
Model name: 
abc xyz 

这个怎么样:

<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 

这种转变

<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