当XML以以下形式出现时,我无法解析它:

<Cars>
    <Car>
        <Color>Blue</Color>
        <Make>Ford</Make>
        <Model>Mustant</Model>
    </Car>
    <Car>
        <Color>Red</Color>
        <Make>Chevy</Make>
        <Model>Camaro</Model>
    </Car>
</Cars>

我已经想出了如何像这样解析一级孩子:
<Car>
    <Color>Blue</Color>
    <Make>Chevy</Make>
    <Model>Camaro</Model>
</Car>

使用这种代码:
from lxml import etree
    a = os.path.join(localPath,file)
    element = etree.parse(a)
    cars = element.xpath('//Root/Foo/Bar/Car/node()[text()]')
    parsedCars = [{field.tag: field.text for field in cars} for action in cars]
    print parsedCars[0]['Make'] #Chevy

如何解析我们的多个“Car”标记,即“Cars”的子标记?

最佳答案

试试这个

from lxml import etree
    a = os.path.join(localPath,file)
    element = etree.parse(a)
    cars = element.xpath('//Root/Foo/Bar/Car')
    for car in cars:
        colors = car.xpath('./Color')
        makes = car.xpath('./Make')
        models = car.xpath('./Model')

关于python - 使用lxml和Python解析嵌套的xml,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9618329/

10-13 08:59