我一直在用
lxml
和
objectify
要阅读到目前为止的XML:
-
我创建了与标记同名的自定义类
-
我曾经
对于
循环读取对象化的xml标记,并将它们映射到我的自定义类中
由于我不需要保留标签序列,所以上述技术起到了作用。
然而,现在,我有一个新的挑战。
检查以下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
.