使用XPATH读取棘手的XML

时间:2015-11-14 12:42:19

标签: python lxml

我是Python的初学者& XPATH并且需要使用XPATH读取具有非均匀节点的XML(类似于下面提到的节点)。要写入文件的输出格式也如下所示。该代码使用lxml库。

请帮我构建一个正确的XPATH。

源XML

<Classes>
    <German>
        <Student>
            <Span><a href="">John</a></Span>
        </Student>
        <Student>
            <Span>Adam</Span>
        </Student>
    </German>
    <English>
        <Student>
            <Span>Mary</Span>
        </Student>
    </English>
    <French>
        <Student>
            <Span><a href="">Anil</a></Span>
        </Student>
        <Student>
            <Span><a href="">Jack</a></Span>
        </Student>
    </French>
    <Spanish>
        <Student>
            <Span>Mary</Span>
        </Student>
        <Student>
            <Span>Jack</Span>
        </Student>
    </Spanish>
</Classes>

预期输出

German
    John
    Adam
English
    Mary
French
    Anil
    Jack
Spanish
    Mary
    Jack

谢谢, NIKHIL

1 个答案:

答案 0 :(得分:0)

此代码有助于:

from lxml import html

xml_content = """<Classes>
    <German>
        <Student>
            <Span><a href="">John</a></Span>
        </Student>
        <Student>
            <Span>Adam</Span>
        </Student>
    </German>
    <English>
        <Student>
            <Span>Mary</Span>
        </Student>
    </English>
    <French>
        <Student>
            <Span><a href="">Anil</a></Span>
        </Student>
        <Student>
            <Span><a href="">Jack</a></Span>
        </Student>
    </French>
    <Spanish>
        <Student>
            <Span>Mary</Span>
        </Student>
        <Student>
            <Span>Jack</Span>
        </Student>
    </Spanish>
</Classes>"""

tree = html.fromstring(xml_content)
classes = tree.xpath('//classes/*')
for language_class in classes:
    print language_class.tag.capitalize()
    for student in language_class.xpath('.//student/span//text()'):
        print "    {}".format(student)

<强>输出:

German
    John
    Adam
English
    Mary
French
    Anil
    Jack
Spanish
    Mary
    Jack