Reputation: 27
I have given an XML file tried to read it in Python using the following code:
import xml.etree.ElementTree as ETree
parser = ETree.XMLParser(encoding="utf-8")
tree = ETree.parse("real.xml", parser=parser)
I was getting the error, so I tried to open the XML in Notepad++ and notice the file is not in XML formate exactly:
> 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>'
Above is the example of the XML given, how I should handle this in python.
Upvotes: 0
Views: 231
Reputation: 2469
Try this lib.
real.xml
<?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>
example
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])
Result:
[('n52383', 'int', '52'), ('n80958', 'int', '81'), ('n21669', 'int', '22')]
[('n52383', 'str', '292 Lennox Street'), ('n80958', 'str', '72 Jones Road')]
Here are more examples: https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples
Upvotes: 1