XSLT使用查找

时间:2011-08-10 04:20:34

标签: xml xslt lookup

我正在尝试将XML文档转换为另一个XML文档。我尝试了各种方法,但都没有产生所需的目标XML文档。

我有一个假设的输入XML文档,如下所示:

<rows>
 <row>
  <name>ON</name>
  <description/>
 </row>
 <row>
  <name>NY</name>
  <description/>
 </row>
</rows>

我还有两个查找:

<loc:locations>
 <loc:location>
  <loc:code>ON</loc:code>
  <loc:value>Ontario</loc:value>
 </loc:location>
 <loc:location>
  <loc:code>NY</loc:code>
  <loc:value>New York</loc:value>
 </loc:location>
</loc:locations>

<des:descriptions>
 <des:description>
  <des:code>ON</des:code>
  <des:value>Ontario is a province in Canada</des:value>
 </des:description>
 <des:description>
  <des:code>NY</des:code>
  <des:value>New York is a state in the USA</des:value>
 </des:description>
</des:descriptions>

我希望将输入XML转换为此目标XML:

<places>
 <place>
  <name>Ontario</name>
  <description>Ontario is a province in Canada</description>
 </place>
 <place>
  <name>New York</name>
  <description>New York is a state in the USA</description>
 </place>
</places>

什么是XSLT才能实现这一目标?谢谢!

2 个答案:

答案 0 :(得分:2)

这对我有用Xalan

<xsl:transform 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:loc="http://sample.com/location"
  xmlns:des="http://sample.com/description"
  version="1.0">

 <xsl:output method="xml"/>

 <xsl:variable name="locations" select="document('locations.xml')/loc:locations/loc:location"/>
 <xsl:variable name="descriptions" select="document('descriptions.xml')/des:descriptions/des:description"/>

 <xsl:template match="/">
    <places>
      <xsl:apply-templates/>
    </places>
 </xsl:template>

 <xsl:template match="//row">
  <xsl:variable name="name" select="name/text()"/>
  <place>
    <name><xsl:value-of select="$locations[loc:code = $name]/loc:value"/></name>
    <description><xsl:value-of select="$descriptions[des:code = $name]/des:value"/></description>
  </place>
 </xsl:template>

</xsl:transform>

答案 1 :(得分:2)

为了便于阅读,为了便于阅读,因为您采用了命名空间约定,您还可以方便地将所有查找数据保存到单个变量中。同时使用current()访问当前节点的name。避免使用//

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:loc="http://sample.com/location"
    xmlns:des="http://sample.com/description"
    version="1.0">

    <xsl:variable name="lookup" 
        select="document('locations.xml')/loc:locations/loc:location
        | document('descriptions.xml')/des:descriptions/des:description"/>

    <xsl:template match="rows">
        <places>
            <xsl:apply-templates/>
        </places>
    </xsl:template>

    <xsl:template match="row">
        <place>
            <name>
                <xsl:value-of select="$lookup[loc:code=current()/name]/
                    loc:value"/>
            </name>
            <description>
                <xsl:value-of select="$lookup[des:code=current()/name]/
                    des:value"/>
            </description>
        </place>
    </xsl:template>

</xsl:stylesheet>