【发布时间】:2013-06-20 23:06:20
【问题描述】:
XML:
<?xml version="1.0"?>
<pages>
<page>
<url>http://example.com/Labs</url>
<title>Labs</title>
<subpages>
<page>
<url>http://example.com/Labs/Email</url>
<title>Email</title>
<subpages>
<page/>
<url>http://example.com/Labs/Email/How_to</url>
<title>How-To</title>
</subpages>
</page>
<page>
<url>http://example.com/Labs/Social</url>
<title>Social</title>
</page>
</subpages>
</page>
<page>
<url>http://example.com/Tests</url>
<title>Tests</title>
<subpages>
<page>
<url>http://example.com/Tests/Email</url>
<title>Email</title>
<subpages>
<page/>
<url>http://example.com/Tests/Email/How_to</url>
<title>How-To</title>
</subpages>
</page>
<page>
<url>http://example.com/Tests/Social</url>
<title>Social</title>
</page>
</subpages>
</page>
</pages>
代码:
// rexml is the XML string read from a URL
from xml.etree import ElementTree as ET
tree = ET.fromstring(rexml)
for node in tree.iter('page'):
for url in node.iterfind('url'):
print url.text
for title in node.iterfind('title'):
print title.text.encode("utf-8")
print '-' * 30
输出:
http://example.com/article1
Article1
------------------------------
http://example.com/article1/subarticle1
SubArticle1
------------------------------
http://example.com/article2
Article2
------------------------------
http://example.com/article3
Article3
------------------------------
Xml 表示站点地图的树状结构。
我整天在 docs 和 Google 上翻来覆去,无法弄清楚如何获取条目的节点深度。
我使用了子容器的计数,但这仅适用于第一个父容器,然后它中断,因为我无法弄清楚如何重置。但这可能只是一个骇人听闻的想法。
想要的输出:
0
http://example.com/article1
Article1
------------------------------
1
http://example.com/article1/subarticle1
SubArticle1
------------------------------
0
http://example.com/article2
Article2
------------------------------
0
http://example.com/article3
Article3
------------------------------
【问题讨论】:
-
您能提供一个示例 xml 吗?另外,您是否需要计算节点深度 - 我的意思是,是否可以解析 url 本身并计算域名后有多少项目?
-
添加了 XML 示例。我使用的深度最大为 7,并且总页数不超过 500。
-
@tntu,示例似乎坏了。
-
ElementTree 元素在父节点上没有句柄,因此除非您创建某种节点映射,否则不可能返回树来计算特定节点的深度。不过你可以construct that mapping yourself。
标签: python xml xml-parsing