Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用etreepython解析xml_Python_Xml_Xml Parsing_Elementtree_Xml.etree - Fatal编程技术网

用etreepython解析xml

用etreepython解析xml,python,xml,xml-parsing,elementtree,xml.etree,Python,Xml,Xml Parsing,Elementtree,Xml.etree,对于此xml <locations> <location> <locationid>1</locationid> <homeID>281</homeID> <buildingType>Added</buildingType> <address>A</address> <address

对于此xml

<locations>

    <location>
        <locationid>1</locationid>
        <homeID>281</homeID>
        <buildingType>Added</buildingType>
        <address>A</address>
        <address2>This is address2</address2>
        <city>This is city/city>
        <state>State here</state>
        <zip>1234</zip>
    </location>
    <location>
        <locationid>2</locationid>
        <homeID>81</homeID>
        <buildingType>Added</buildingType>
        <address>B</address>
        <address2>This is address2</address2>
        <city>This is city/city>
        <state>State here</state>
        <zip>1234</zip>
    </location>
    .
    .
    .
    .
    <location>
        <locationid>10</locationid>
        <homeID>21</homeID>
        <buildingType>Added</buildingType>
        <address>Z</address>
        <address2>This is address2</address2>
        <city>This is city/city>
        <state>State here</state>
        <zip>1234</zip>
    </location>
</locations>

None
的形式获取输出,我在这里做什么错了?

首先,您的
xml
格式不正确。在发布数据时,您应该更加小心,并尽量避免让其他用户修复您的数据

您可以搜索前面的同级,如:

import urllib2
import lxml.etree as ET

url="..."
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
for target in root.xpath('.//location/address[text()="A"]'):                                                                                                  
    for location in [e for e in target.itersiblings(preceding=True) if e.tag == "locationid"]:                                                                
        print location.text
或者直接从
xpath
表达式执行,如:

import urllib2
import lxml.etree as ET

url="..."
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
print root.xpath('.//location/address[text()="A"]/preceding-sibling::locationid/text()')[0]
按如下方式运行其中一个:

python2 script.py
这意味着:

1

请尝试此“//location/[normalize space(address)=“A”]”@Naren谢谢,尝试了此操作但无效。很抱歉,我的xml出现了一些错误。下次我会处理的。谢谢
1