簡體   English   中英

有沒有一種簡單的方法來在Python中操作XML文檔?

[英]Is there an easy way to manipulate XML documents in Python?

我已經圍繞這個問題做了一些研究,但還沒有真正能夠提出任何有用的東西。 我需要的不僅是解析和讀取,而是實際操作python中的XML文檔,類似於JavaScript能夠操作HTML文檔的方式。

請允許我舉個例子。 說我有以下XML文檔:

<library>
    <book id=123>
        <title>Intro to XML</title>
        <author>John Smith</author>
        <year>1996</year>
    </book>
    <book id=456>
        <title>XML 101</title>
        <author>Bill Jones</author>
        <year>2000</year>
    </book>
    <book id=789>
        <title>This Book is Unrelated to XML</title>
        <author>Justin Tyme</author>
        <year>2006</year>
    </book>
</library>

我需要一種方法既能檢索元素,無論是使用XPath或用“Python化”的方法,如概括在這里 ,但我也需要能夠操縱的文檔,如下面:

>>>xml.getElement('id=123').title="Intro to XML v2"
>>>xml.getElement('id=123').year="1998"

如果有人知道Python中的這樣一個工具,請告訴我。 謝謝!

如果要避免安裝lxml.etree ,可以使用標准庫中的xml.etree

這是Acorn的答案移植到xml.etree

import xml.etree.ElementTree as et  # was: import lxml.etree as et

xmltext = """
<root>
    <fruit>apple</fruit>
    <fruit>pear</fruit>
    <fruit>mango</fruit>
    <fruit>kiwi</fruit>
</root>
"""

tree = et.fromstring(xmltext)

for fruit in tree.findall('fruit'): # was: tree.xpath('//fruit')
    fruit.text = 'rotten %s' % (fruit.text,)

print et.tostring(tree) # removed argument: prettyprint

注意:如果我能以清晰的方式做到這一點,我會把它作為對Acorn答案的評論。 如果您喜歡這個答案,請給予Acorn upvote。

lxml允許您使用XPath選擇元素,並且還可以操作這些元素。

import lxml.etree as et

xmltext = """
<root>
    <fruit>apple</fruit>
    <fruit>pear</fruit>
    <fruit>mango</fruit>
    <fruit>kiwi</fruit>
</root>
"""

tree = et.fromstring(xmltext)

for fruit in tree.xpath('//fruit'):
    fruit.text = 'rotten %s' % (fruit.text,)

print et.tostring(tree, pretty_print=True)

結果:

<root>
    <fruit>rotten apple</fruit>
    <fruit>rotten pear</fruit>
    <fruit>rotten mango</fruit>
    <fruit>rotten kiwi</fruit>
</root>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM