重新排列XML元素并从其值中提取相关数据

时间:2012-08-21 14:55:40

标签: xml xslt xpath

我想重新排列XML元素并从每个元素中提取相关值以生成XML或cvs输出。

我在一些材料中读到(xsl:value-of)用于提取元素的值,但我不确定如何使用它来从元素中提取特定值。 这些是XML数据示例

<Add>
<Row>
<L>1</L>
<LD>Dwelling  (Part Of), Null</LD>
<th>NULL</th>
<AA>Abesinia Passage</AA>
<LN>Dwelling  (Part Of)</LN>
</Row>

例如,我想从(Addressarea)元素中提取任何具有Estate或island作为后缀的值。

我还想从(通道)元素中删除带有后缀Estate或island的任何NULL值或值。

1 个答案:

答案 0 :(得分:0)

此转化

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pOrder" select=
  "'|LocatorDesignator|LocatorName|Locator|thoroughfare|addressArea|'"/>

 <xsl:variable name="vOrder" select="document('')/*/xsl:param[@name='pOrder']/*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="Rowinfo">
  <xsl:copy>
   <xsl:apply-templates select="*">
     <xsl:sort data-type="number" select=
     "string-length(substring-before($pOrder, concat('|', name(), '|')))"/>
   </xsl:apply-templates>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

应用于以下XML文档(由上一个问题的答案生成):

<Address>
   <Rowinfo>
      <Locator>1</Locator>
      <LocatorDesignator>Null, Dwelling  (Part Of)</LocatorDesignator>
      <thoroughfare>Abesinia Passage</thoroughfare>
      <LocatorName>Dwelling  (Part Of)</LocatorName>
      <addressArea>Some Address Area</addressArea>
   </Rowinfo>
   <Rowinfo>
      <Locator>1a</Locator>
      <LocatorDesignator>Null, Edmund's Home</LocatorDesignator>
      <thoroughfare>Arena's Palace Lane</thoroughfare>
      <LocatorName>Edmund's Home</LocatorName>
      <addressArea>Some Other Address Area</addressArea>
   </Rowinfo>
</Address>

生成想要的正确结果

<Address>
    <Rowinfo>
        <LocatorDesignator>Null, Dwelling  (Part Of)</LocatorDesignator>
        <LocatorName>Dwelling  (Part Of)</LocatorName>
        <Locator>1</Locator>
        <thoroughfare>Abesinia Passage</thoroughfare>
        <addressArea>Some Address Area</addressArea>
    </Rowinfo>
    <Rowinfo>
        <LocatorDesignator>Null, Edmund's Home</LocatorDesignator>
        <LocatorName>Edmund's Home</LocatorName>
        <Locator>1a</Locator>
        <thoroughfare>Arena's Palace Lane</thoroughfare>
        <addressArea>Some Other Address Area</addressArea>
    </Rowinfo>
</Address>