【问题标题】:Extracting Raw XML via lxml etree通过 lxml etree 提取原始 XML
【发布时间】:2019-05-29 13:48:00
【问题描述】:

我正在尝试从 XML 文件中提取原始 XML。

所以如果我的数据是:

        <xml>
            ... Lots of XML ...

            <getThese>
                <clonedKey>1</clonedKey>
                <clonedKey>2</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>this is a sentence</randomStuff>
            </getThese>         
            <getThese>
                <clonedKey>6</clonedKey>
                <clonedKey>8</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>more words</randomStuff>
            </getThese>

            ... Lots of XML ...

        </xml>

我可以使用 etree 轻松获得我想要的密钥:

from lxml import etree
search_me = etree.fromstring(xml_str)
search_me.findall('./xml/getThis')

但是如何将实际内容作为原始 XML 获取?我在文档中看到的所有内容都是用于获取元素/文本/属性而不是原始 XML。

我想要的输出是一个包含两个元素的列表:

["<getThese>
                <clonedKey>1</clonedKey>
                <clonedKey>2</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>this is a sentence</randomStuff>
            </getThese>",
"<getThese>
                <clonedKey>6</clonedKey>
                <clonedKey>8</clonedKey>
                <clonedKey>3</clonedKey>
                <randomStuff>more words</randomStuff>
            </getThese>"]

【问题讨论】:

  • 也许你想使用正则表达式

标签: python python-3.x lxml


【解决方案1】:

您应该可以使用tostring() to serialize XML。

示例...

from lxml import etree

xml = """
<xml>
    <getThese>
        <clonedKey>1</clonedKey>
        <clonedKey>2</clonedKey>
        <clonedKey>3</clonedKey>
        <randomStuff>this is a sentence</randomStuff>
    </getThese>         
    <getThese>
        <clonedKey>6</clonedKey>
        <clonedKey>8</clonedKey>
        <clonedKey>3</clonedKey>
        <randomStuff>more words</randomStuff>
    </getThese>
</xml>
"""

parser = etree.XMLParser(remove_blank_text=True)

tree = etree.fromstring(xml, parser=parser)

elems = []

for elem in tree.xpath("getThese"):
    elems.append(etree.tostring(elem).decode())

print(elems)

打印输出...

['<getThese><clonedKey>1</clonedKey><clonedKey>2</clonedKey><clonedKey>3</clonedKey><randomStuff>this is a sentence</randomStuff></getThese>', '<getThese><clonedKey>6</clonedKey><clonedKey>8</clonedKey><clonedKey>3</clonedKey><randomStuff>more words</randomStuff></getThese>']

【讨论】:

  • 优秀。我确实看到并尝试了tostring(),但显然我做错了;它不是 Element 方法,而是 etree 方法!谢谢,这很好用。
猜你喜欢
  • 1970-01-01
  • 2011-04-29
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
相关资源
最近更新 更多