21

I am learning ElementTree in python. Everything seems fine except when I try to parse the xml file with prefix:

test.xml:

<?xml version="1.0"?>
<abc:data>
   <abc:country name="Liechtenstein" rank="1" year="2008">
   </abc:country>
   <abc:country name="Singapore" rank="4" year="2011">
   </abc:country>
   <abc:country name="Panama" rank="5" year="2011">
   </abc:country>
</abc:data>

When I try to parse the xml:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')

I got the following error:

xml.etree.ElementTree.ParseError: unbound prefix: line 2, column 0

Do I need to specify something in order to parse a xml file with prefix?

Pedro Romano
  • 10,519
  • 3
  • 42
  • 49
Kintarō
  • 2,707
  • 7
  • 40
  • 70

2 Answers2

19

Add the abc namespace to your xml file.

<?xml version="1.0"?>
<abc:data xmlns:abc="your namespace">
Thiru
  • 3,003
  • 7
  • 34
  • 49
  • 33
    But what about when it's not my XML to change, I just need to parse it? – Mark Allen Mar 06 '15 at 01:28
  • 3
    I second the question/comment from @Mark Allen! I am having the same problem. Certainly on a case-by-case basis one could edit the file, but I have many large (and nonuniform) xml files. Surely there is a way to get around this – dnh37 Aug 04 '16 at 06:46
0

See if this works:

from bs4 import BeautifulSoup

xml_file = "test.xml"

with open(xml_file, "r", encoding="utf8") as f:
    contents = f.read()
    soup = BeautifulSoup(contents, "xml")

    items = soup.find_all("country")
    print (items)

The above will produce an array which you can then manipulate to achieve your aim (e.g. remove html tags etc.):

[<country name="Liechtenstein" rank="1" year="2008">
</country>, <country name="Singapore" rank="4" year="2011">
</country>, <country name="Panama" rank="5" year="2011">
</country>]
polars
  • 1