首页 > 解决方案 > 如何读取 XML 并保留标签序列以保持其含义完整?

问题描述

到目前为止,我一直在使用lxmlobjectify阅读 XML:

  1. 我创建了与标签同名的自定义类
  2. 我使用for循环来读取对象化的 xml-tags 并将它们映射到我的自定义类中

上述技术有效,因为我不需要保留标签序列。

然而,现在,我有一个新的挑战。

检查以下 XML 文件:

<member>
    <detaileddescription>
        Hello
        <formula id="39">my</formula>
        name
        <formula id="102">is</formula>
        Buddy.
        <formula id="103">I</formula>
        am a
        <itemizedlist>
            <listitem>
            superhero
            <formula id="104">.</formula>
            </listitem>
            <listitem>
                At least,
                <formula id="105">I think</formula>
            </listitem>
        </itemizedlist>
        so...:)
        <simplesect kind="see">
            What
            <ref refid="ref_id" kindref="ref_kindref">do you</ref>
            <bold>think</bold> ?
        </simplesect>
        Let me know.
    </detaileddescription>
 </member>

我的任务是阅读它并在标签之间保留其含义。

我做了很多实验。但是,我一直未能成功找到方法。

from lxml import etree, objectify


def to_list(root):
    my_list = []
    for item in root.iter():
        if item.text is not None:
            text = item.text.strip()
            if text is not "":
                my_list.append("text####" + text)

        if item.tail is not None:
            tail = item.tail.strip()
            if tail is not "":
                my_list.append("tail####" + tail)
    return my_list

if __name__ == '__main__':
    in_file = r"xml.xml"

    class_dom = etree.parse(in_file)
    class_xml_bin = etree.tostring(class_dom, pretty_print=False, encoding="ascii")
    class_xml_text = class_xml_bin.decode()
    root = objectify.fromstring(class_xml_text)

    my_list = to_list(root.detaileddescription)

    for item in my_list:
        print(item)

输出:

text####Hello
text####my
tail####name
text####is
tail####Buddy.
text####I
tail####am a
tail####so...:)
text####superhero
text####.
text####At least,
text####I think
text####What
tail####Let me know.
text####do you
text####think
tail####?

在这里你可以看到输出没有完全保持准确的顺序。比如,so...:)不合时宜。

此解决方案的另一个主要问题是,它不会将 XML 内容保留为类。而是直接输出文本。

有没有人有什么建议?

注意:我不能使用xpath

标签: pythonxmllxmllxml.objectify

解决方案


推荐阅读