如何选择XML节点并保留文档结构

时间:2013-11-13 17:23:37

标签: xml xpath

XML:

    <root>
      <rows>
        <row hash="156458">
          <column name="Id">1</column>
          <column name="Nome">Evandro</column>
          <column name="CPF">98765432100</column>
        </row>
        <row hash="52458">
          <column name="Id">2</column>
          <column name="Nome">Everton</column>
          <column name="CPF">12345678900</column>
        </row>
      </rows>
    </root>

XPath查询:

./root/rows/row/column[@name='Nome'] | ./root/rows/row/column[@name='CPF']

XPath返回:

    <root>
      <column name="Nome">Evandro</column>
      <column name="CPF">98765432100</column>
      <column name="Nome">Everton</column>
      <column name="CPF">12345678900</column>
    </root>

我希望XPath回归:

    <root>
      <rows>
        <row hash="156458">
          <column name="Nome">Evandro</column>
          <column name="CPF">98765432100</column>
        </row>
        <row hash="52458">
          <column name="Nome">Everton</column>
          <column name="CPF">12345678900</column>
        </row>
      </rows>
    </root>

我想在进行查询时使xpath保留文档结构。

1 个答案:

答案 0 :(得分:1)

XPath非常适合选择,但不适合结构化。升级到完整的XSLT。您只需要一个简单的基于身份的转换......

鉴于此XML输入:

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <rows>
    <row hash="156458">
      <column name="Id">1</column>
      <column name="Nome">Evandro</column>
      <column name="CPF">98765432100</column>
    </row>
    <row hash="52458">
      <column name="Id">2</column>
      <column name="Nome">Everton</column>
      <column name="CPF">12345678900</column>
    </row>
  </rows>
</root>

此XSLT转换:

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

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

  <xsl:template match="column[@name='Id']"/>

</xsl:stylesheet>

将生成所需的XML输出:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <rows>
      <row hash="156458">
         <column name="Nome">Evandro</column>
         <column name="CPF">98765432100</column>
      </row>
      <row hash="52458">
         <column name="Nome">Everton</column>
         <column name="CPF">12345678900</column>
      </row>
   </rows>
</root>

备注:

  • 第一个模板是识别模板;它将复制节点 输入到输出,除非更具体的模板覆盖它。
  • 第二个模板是省略Id column s。
  • 的覆盖