簡體   English   中英

在 PYTHON 中解析不同格式的 XML 文件

[英]Parsing XML file in PYTHON with different format

我給出了一個 XML 文件,嘗試使用以下代碼在 Python 中讀取它:

import xml.etree.ElementTree as ETree
parser = ETree.XMLParser(encoding="utf-8")
tree = ETree.parse("real.xml", parser=parser)

我收到錯誤消息,因此我嘗試在 Notepad++ 中打開 XML,並注意到該文件並非完全采用 XML 格式:

> b'<?xml version="1.0" encoding="UTF-8" ?><root><id type="dict"><n123
> type="int">52</n123><n124 type="int">81</n124><n125
> type="int">22</n125><n126 type="int">94</n126><n127
> type="int">42</n127><n128 type="int">54</n128><n129
> type="int">94</n129><n130 type="int">34703</n130><n131
> type="int">20 ......... 
 </n141><n142 type="int">1</n142><n143
> type="int">2</n143></root>'

上面是給出的 XML 示例,我應該如何在 python 中處理它。

試試這個庫。

真實文件

<?xml version="1.0" encoding="UTF-8" ?>
<root>
<id type="dict">
    <n52383 type="int">52</n52383><n80958 type="int">81</n80958><n21669 type="int">22</n21669>
</id>
<address type=''dict''>
    <n52383 type="str">292 Lennox Street</n52383><n80958 type="str">72 Jones Road</n80958> ...........
</address>
</root>

例子

from simplified_scrapy import SimplifiedDoc, utils
xml = utils.getFileContent('real.xml')
doc = SimplifiedDoc(xml)

ids = doc.select('id').children
print([(id.tag,id['type'],id.text) for id in ids])

addresses = doc.select('address').children
print([(addr.tag,addr['type'],addr.text) for addr in addresses])

結果:

[('n52383', 'int', '52'), ('n80958', 'int', '81'), ('n21669', 'int', '22')]
[('n52383', 'str', '292 Lennox Street'), ('n80958', 'str', '72 Jones Road')]

這里有更多例子: https : //github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM