【问题标题】:How to get the complete xml with just the required element如何仅使用所需元素获取完整的 xml
【发布时间】:2014-05-19 12:53:31
【问题描述】:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
for i in tree.findall('.//rank'):
    print ET.tostring(i)

这里我想获取所有排名元素(保持其绝对结构)

我得到的输出为

<rank>1</rank>

<rank>4</rank>

<rank>68</rank>

我应该怎么做才能得到输出为

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
    </country>
    <country name="Singapore">
        <rank>4</rank>
    </country>
    <country name="Panama">
        <rank>68</rank>
    </country>
</data>

当输入xml文件country_data.xml为

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/> First Country
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/> Second Country
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/> Third Country
    </country>
</data>

【问题讨论】:

    标签: python xml xpath elementtree


    【解决方案1】:

    您可以使用 Python + XSLT 来实现。首先,您需要一个 XSLT 文档。下面的一个进行你需要的转换(你可以测试它here):

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output indent="yes"/>
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"></xsl:apply-templates>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="year|gdppc|neighbor|country/text()" />
    </xsl:stylesheet>
    

    您可以使用LXML 在 Python 中转换 XSLT:

    import lxml.etree as etree
    
    source = etree.parse("data.xml")
    xsldoc = etree.parse("stylesheet.xsl")
    transform = etree.XSLT(xsldoc)
    result = transform(source)
    print(etree.tostring(result, pretty_print=True))
    

    这个变换的结果是:

    <?xml version="1.0" encoding="UTF-8"?>
    <data>
        <country name="Liechtenstein">
          <rank>1</rank>
       </country>
        <country name="Singapore">
          <rank>4</rank>
       </country>
        <country name="Panama">
          <rank>68</rank>
       </country>
    </data>
    

    【讨论】:

      【解决方案2】:

      一个简单的解决方案可能是删除所有不是datacountryrank的元素,然后输出根元素。

      另一种方法是使用data 根创建一个新文档,然后遍历所有rank 元素,获取它们的直接父元素,将它们作为子元素复制到data(具有所有必要属性),然后添加rank 元素的副本。

      但由于 elementtree 不保留父引用,因此您需要一些解决方法:access ElementTree node parent node

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        相关资源
        最近更新 更多