[ACCEPTED]-python parse xml text-xml
From a file, you could normally do it as
from xml.dom import minidom
xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml')
For 1 a string, you can change it to
from xml.dom import minidom
xmldoc = minidom.parseString( Your string goes here )
You could use: xml.dom.minidom.parseString(text)
This method creates a StringIO 4 object for the string and passes that on 3 to parse().
You could also use the same technique 2 of using StringIO for any other XML parser 1 that expects a file-like object.
import StringIO
your_favourite_xml_parser.parse(StringIO.StringIO('<xml>...</xml>'))
You can use (xml.etree.cElementTree) also.
import xml.etree.cElementTree as ET
aElement = ET.fromstring('<Root id="UUID_1"><Item id="id_Item" /></Root>')
See Python help document
Each element has a number of properties associated with it:
a tag which is a string identifying what kind of data this element represents (the element type, in other words).
a number of attributes, stored in a Python dictionary.
a text string.
an optional tail string.
a number of child elements, stored in a Python sequence
0
You can also use lxml. My startup (http://dealites.com) involves 7 a lot of XML processing everyday. I have 6 tried almost every xml library available 5 in python. lxml is the best library available 4 for xml processing.
You can also try Beautiful 3 soup. It is great for HTML parsing but a 2 good alternative to lxml.
lxml example:
from lxml import etree;
parsedfeed = etree.xml('your xml here');
Beautiful 1 Soup example:
from BeautifulSoup import BeautifulStoneSoup;
soup = BeautifulStoneSoup('your xml here');
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.