使用BeautifulSoup和Python中的lxml删除xml中的标记及其内容



我正在处理我的Evernote数据——提取到一个xml文件中。我已经使用BeautifulSoup解析了数据,下面是我的xml数据示例。

<note>
<title>
 Audio and camera roll from STUDY DAY! in San Francisco
</title>
<content>
<![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note><div><en-media type="image/jpeg" hash="e3a84de41c9886b93a6921413b8482d5" width="1080" style="" height="1920"/><en-media type="image/jpeg" hash="b907b22a9f2db379aec3739d65ce62db" width="1123" style="" height="1600"/><en-media type="audio/wav" hash="d3fdcd5a487531dc156a8c5ef6000764" style=""/><br/></div>
</en-note>
]]>
</content>
<created>
 20130217T153800Z
</created>
<updated>
 20130217T154311Z
</updated>
<note-attributes>
<latitude>
 37.78670730072799
</latitude>
<longitude>
 -122.4171893858559
</longitude>
<altitude>
 42
</altitude>
<source>
 mobile.iphone
</source>
<reminder-order>
 0
</reminder-order>
</note-attributes>
<resource>
<data encoding="base64">

我想在这里探索两条途径:1.查找和删除特定标签(在这种情况下)2.定位要提取到另一文档的标签组/列表

这是我当前的代码,它解析xml并将其美化并输出到文本文件中。

from bs4 import BeautifulSoup
soup = BeautifulSoup(open('myNotes.xml','r'))
with open("file.txt", "w") as f:
f.write(soup.prettify().encode('utf8'))

您可以按名称搜索节点

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open('myNotes.xml', 'r'))

source = soup.source
print source
#<source>
# mobile.iphone
#</source>

source = soup.source
print source.string
# mobile.iphone

另一种方法是findAll方法:

for tag in soup.findAll('source'):
    print tag.string

如果你想打印每个节点剥离标签,这应该做的工作:

for tag in soup.findAll():
    print tag.string

希望能有所帮助。

编辑:_________

BeautifulSoup表示您知道其结构,尽管根据定义xml是一种结构化数据存储。因此,您需要给BS一个解析xml的指南。

row = []
title = soup.note.title.string
created = soup.note.created.string
row.append(title)
row.append(created)

现在您只需要对xml进行迭代。

如果使用BeautifulSoup,可以使用getText()方法去掉子元素中的标记,得到一个合并的文本

source.getText()

最新更新