我有一个xml文件,如下所示:
<page>
<title>title1</title>
<subtitle>subtitle</subtitle>
<ns>0</ns>
<id>1</id>
<text>hello world!@</text>
</page>
<page>
<title>title2</title>
<ns>0</ns>
<id>1</id>
<text>hello world</text>
</page>
我怎样才能得到每页的正文?现在我有每一页的清单。下面的代码将打印第二个page元素的文本,而不是第一个。是否有方法按标记名获取子元素,如element['text']
for i in pages:
print i[3]
为了简化这个问题,我使用了一个“Node”助手类来返回dict:
示例用法:
结果:
This tutorial帮助我完成了类似的任务:
每次迭代都会找到一个名为“id”或“text”的标记。如果找不到标记,则返回字符串“None”。一次迭代的结果将被追加到一个列表中,允许我们以类似于数据帧的格式打印该列表。
结果:
如果只想打印文本,只需删除id行即可。
您可以编写如下代码:
结果将是:
相关问题 更多 >
编程相关推荐