XSLT按给定的XML结构顺序排列

时间:2016-08-16 09:37:42

标签: xml xslt

我有一个XML结构如下:

// Specific method handler takes priority over general.
const method &mtd = msg.method();
if(m_supported_methods.count(mtd))
{
    m_supported_methods[mtd](msg);
}
else if(mtd == methods::OPTIONS)
{
    handle_options(msg);
}

XSLT是:

<root>
   <node1> 
         <name>John</name> 
   </node1>
   <node1> 
         <name>Rita</name> 
   </node1>
   <node2> 
         <city>Irvine</city> 
   </node2>
   <node1> 
         <name>Kate</name> 
   </node1>
   <node2> 
         <city>LA</city> 
   </node2>
<root>

我需要一个输出:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">   
  <xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
  <xsl:template match="/">
    <Details>
      <xsl:for-each select="/root">       
          <xsl:for-each select="node1">
                <xsl:if test="name!=''"  >
                   <Name>
                    <xsl:value-of select="name"/>
                   </Name>
                </xsl:if>
          </xsl:for-each>
          <xsl:for-each select="node2">
                <xsl:if test="city>!=''"  >
                   <City>
                    <xsl:value-of select="city>"/>
                   </City>
                </xsl:if>
          </xsl:for-each>
     </xsl:for-each>
    </Details>
    </xsl:template>
</xsl:stylesheet>

但我得到以下输出:

    <Details xmlns:PP="http://www.w3.org/2001/XMLSchema/Details.xsd">
      <Name>John</Name>
      <Name>Rita</Name>
      <City>Irvine</City>
      <Name>Kate</Name>
      <City>LA</City>
    </Details>

请帮助。

1 个答案:

答案 0 :(得分:0)

使用此xslt模板:

<?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">   
      <xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
      <xsl:template match="/">
        <Details>
          <xsl:for-each select="/root/*/*/.">
                <xsl:copy-of select= "."/>
          </xsl:for-each>
        </Details>
        </xsl:template>
    </xsl:stylesheet>