在Python中解析XML
我想从一个xml文件中提取文本。假设我在一个file.xml文件里有一些内容:
<s id="1792387-2">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>
我该如何从上面的内容中提取以下文本:
Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).
然后在对这些文本进行一些修改后,我想把修改后的文本用相同的标签返回,如下所示。
<s id="1792387-2"> Changed Text </s>
有什么建议吗?谢谢!
3 个回答
1
使用Python中的dom包来解析XML文件是我最喜欢的方法,具体可以参考这个链接:http://docs.python.org/py3k/library/xml.dom.minidom.html。
import xml.dom.minidom
d = xml.dom.minidom.parseString("<s id=\"1792387-2\">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>")
oldText = d.childNodes[0].childNodes[0].data
d.childNodes[0].childNodes[0].data = "Changed text"
d.toxml()
不过,这个方法并不能帮助你解析文本,所以我不太确定你具体想要什么。
4
有几个标准库的方法可以用来解析XML文件……但一般来说,ElementTree 是最简单的选择:
from xml.etree import ElementTree
from StringIO import StringIO
doc = ElementTree.parse(StringIO("""<doc><s id="1792387-2">Castro…</s><s id="1792387-3">Other stuff</s></doc>"""))
for elem in doc.findall("s"):
print "Text:", elem.text
elem.text = "new text"
print "New:", ElementTree.dump(elem)
如果你的XML文件是从文件中读取的,你可以使用:
f = open("path/to/foo.xml")
doc = ElementTree.parse(f)
f.close()
… use `doc` …
5
LXML 让这个过程变得特别简单。
>>> from lxml import etree
>>> text = '''<s id="1792387-2">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>'''
>>> def edit(s):
... return 'Changed Text'
...
>>> t = etree.fromstring(text)
>>> t.text = edit(t.text)
>>> etree.tostring(t)
'<s id="1792387-2">Changed Text</s>'