我尝试使用Python从混合内容文档中提取多个XML元素。用例是包含电子邮件文本但包含多个XML树的电子邮件。
以下是示例文档:
Email text email text email text email text.
email signature email signature.
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
Email text email text email text email text.
email signature email signature.
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
Email text email text email text email text.
email signature email signature.
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
Email text email text email text email text.
email signature email signature.
我想提取XML树,以便它们可以在for循环中由XML解析器解析。我已经完善了对XML的解析,如果我采用其中一个XML树并直接解析它,它的工作就像一个魅力。
有关如何提取XML树的任何建议吗?此示例也过于简化,电子邮件文本和签名在我的每个示例中都不同,因此唯一可靠的文本是XML树的开头和结尾。
答案 0 :(得分:4)
问题:我想提取XML树,以便XML解析器解析它们
你真的想要获得多个XML树吗?
我想建议使用多个<book
子元素制作一个 XML树。
然而,这就是你想要的:
xml_tag = "<?xml"
catalog_end_tag = "</catalog>"
xml_tree = []
_xml = False
with open('test/Mixed_email_xml') as fh:
while True:
line = fh.readline()
if not line: break
if line.find(xml_tag) >=0:
_xml = True
if _xml:
xml_tree.append(line)
if line.find(catalog_end_tag) >=0:
_xml = False
for line in xml_tree:
print('{}'.format(line[:-1]))
使用Python测试:3.4.2
答案 1 :(得分:4)
最简单的方法:
import re
from lxml import etree
with open('email.txt') as f:
catalogs = ''.join(re.findall('<catalog.*?</catalog>', f.read(), re.S))
root = etree.fromstring('<?xml version="1.0"?><root>{}</root>'.format(catalogs))
然后您可以使用root.iter('book')
迭代所有book
个节点。
答案 2 :(得分:1)
在另一位非常聪明的开发人员的帮助下,这段代码解决了我的问题。
tr1 = "<?xml"
str2 = "</catalog>"
i = 0
ii = 0
tracker = []
final_ls = []
for c in data:
for char in str1:
if data[i + ii] == char:
if ii == len(str1) - 1:
tracker.append(i)
ii += 1
i += 1
ii = 0
for xml in tracker:
ii = 0
i = xml
for c in data[i:]:
if ii == len(str2):
break
ii = 0
for char in str2:
if data[i + ii] == char:
if ii == len(str2) - 1:
final_ls.append(data[xml:i + ii])
ii += 1
else:
ii += 1
i += 1
for ls in final_ls:
print(ls)
答案 3 :(得分:1)
我的第一个想法是使用str方法来分割所有文本,如
t = txt.split(r'<?xml version="1.0"?>')
results = [item.split("</catalog>")[0] + "</catalog>" for item in t if item.startswith("\n<catalog>")]
for i in results:
print(i)
就像代码一样,由明显的分隔符分开。