1

This is my sample xml file:

<?xml version="1.0"?>
<NewSpg>
     <!--Supported Range-->

<ABC data="LS">
   <number Info="0x00" Id="DFS" Bus="0" Device="2" Range="4" Value="0x1A1012f5" no_id="he d kd" /> 
          <number Info="0x32" Id="bhi"  Range="4" Value="0x000012f5" />
          <number Info="0x336" Id="bhi" Range="4" Value="0x00000df2" />
</ABC>
<!--New Info-->
   <NEW_VALUES>
         <Spg:Thing data="First_Thing" Result="true"/>
         <Spg:Thing data="SecondThing" Result="800000000"/>
   </NEW_VALUES>

</NewSpg>

when i try to parse the xml:

import xml.etree.ElementTree as ET
xml_file = "name.xml"
xml_tree = ET.parse(xml_file)
root = xml_tree.getroot()

Following Error occured:

xml.etree.ElementTree.ParseError: unbound prefix: line 13, column 9

I have referred many sites but most of them gives only one solution i.e to provide namespace. But I can't add or delete anything in this xml file. So is there any method by which i can parse this xml file without modifying the file.

V_S
  • 149
  • 6
  • https://stackoverflow.com/questions/13372604/python-elementtree-parsing-unbound-prefix-error – Andrew Ryan Dec 19 '22 at 05:30
  • I have referred this one but the problem is i can't modify my xml file by adding namespace and the second solution provided there requires lxml . – V_S Dec 19 '22 at 05:33
  • you could read in the file as a string make the edit to the namespace and then parse the file with https://stackoverflow.com/questions/647071/python-xml-elementtree-from-a-string-source that is an option though a strange workaround. don't know if there is something cleaner – Andrew Ryan Dec 19 '22 at 05:39

1 Answers1

2

I hope, this will fix your issue (use lxml ETREE)

from lxml import etree
xml_file = "./unbound_prefix.xml"
parser1 = etree.XMLParser(encoding='utf-8', recover=True)
xml_tree = etree.parse(xml_file, parser=parser1)
root = xml_tree.getroot()
root
Muhammad Ali
  • 444
  • 7