gpt4 book ai didi

python - 在Python中解析包含XML的ASCII文本文件

转载 作者:行者123 更新时间:2023-12-01 02:18:25 25 4
gpt4 key购买 nike

我有一个 ASCII 文本文件,其中包含 XML 部分。文件结构如下:

text...
text...
<note1>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note1>
text...
text...
<note2>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note2>
text...
text...

我怎样才能逐步浏览文件并找到 XML 部分并使用 ElementTree 或其他更容易将 XML 部分存储到自己的 XML 文件中的方法?因此文件 1 将为 file1.xml,其中包含以下内容:

<note1>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note1>

那么文件 2 将是 file2.xml ,其中包含以下内容:

<note2>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note2>

最佳答案

BeautifulSoup 在处理格式错误的 XML 方面可以做得很好。在这里你可以简单地做:

from bs4 import BeautifulSoup

with open(textfilename) as fd:
soup = BeautifulSoup(fd)

n1 = soup.findChild() # extract first full XML element, here <node1>...</node1>
while n1:
# process the XML element
...
n1 = n1.findNextSibling() # extract next full XML element

关于python - 在Python中解析包含XML的ASCII文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48161457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com