Python XML检查下一个项目

时间:2014-04-25 08:44:17

标签: python xml python-2.7

这是一个小小的xml示例:

<?xml version="1.0" encoding="UTF-8"?>
<list>
    <person id="1">
        <name>Smith</name>
        <city>New York</city>
    </person>
    <person id="2">
        <name>Pitt</name>
    </person>
    ...
    ...
</list>

现在我需要所有有名字和城市的人。 我试过了:

#!/usr/bin/python
# coding: utf8

import xml.dom.minidom as dom

tree = dom.parse("test.xml")

for listItems in tree.firstChild.childNodes:
    for personItems in listItems.childNodes:
        if personItems.nodeName == "name" and personItems.nextSibling == "city":
            print personItems.firstChild.data.strip()

但是输出是空的。没有&#34;和&#34;条件我成为所有名字。如何在&#34; name&#34;之后检查下一个标签?是&#34; city&#34;?

3 个答案:

答案 0 :(得分:0)

使用元素树检查此element tree

import xml.etree.ElementTree as ET
tree = ET.parse('a.xml')
root = tree.getroot()






for person in root.findall('person'):
    name = person.find('name').text
    try:
        city = person.find('city').text
    except:
        continue
    print name, city

对于id你可以通过id= person.get('id')

获取它
output:Smith New York

答案 1 :(得分:0)

你可以在minidom中执行此操作:

import xml.dom.minidom as minidom

def getChild(n,v):
    for child in n.childNodes:
        if child.localName==v:
            yield child

xmldoc = minidom.parse('test.xml')
person = getChild(xmldoc, 'list')
for p in person:
    for v in getChild(p,'person'):
        attr = v.getAttributeNode('id')
        if attr:
            print attr.nodeValue.strip()    

这将打印人员节点的ID:

1
2

答案 2 :(得分:0)

使用lxml,您可以使用xpath一步到位:

from lxml import etree

xmlstr = """
<list>
    <person id="1">
        <name>Smith</name>
        <city>New York</city>
    </person>
    <person id="2">
        <name>Pitt</name>
    </person>
</list>
"""

xml = etree.fromstring(xmlstr)

xp = "//person[city]"

for person in xml.xpath(xp):
    print etree.tostring(person)

lxml是外部python包,但非常有用,对我来说总是值得安装。

xpath正在搜索任何(//)元素person(由{]的内容声明)子元素city