0

I try to parse the XML file looks like:

<?xml version="1.0" encoding="utf-8"?>
<config>
    <basic logdir = "../log/" workthreadcnt=1 maxday="180" />
</config>

I used xml.dom.minidom, such as:

from xml.dom.minidom import parse
import xml.dom.minidom

domtree = xml.dom.minidom.parse("cfg.xml")

and used xml.etree.ElementTree, such as:

import xml.etree.ElementTree as ET

tree = ET.parse("cfg.xml")

Both of them didn't work until I changed the attribute

workthreadcnt=1

to

workthreadcnt="1"

My questions is: If I insist on using the first format,how to make it work ?

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
  • 4
    Attribute values in XML are always inside quotes. See the specification https://www.w3.org/TR/2008/REC-xml-20081126/#NT-AttValue – Richard Nov 10 '16 at 09:36
  • I think attribute values have to be quoted: http://www.w3schools.com/xml/xml_attributes.asp and http://stackoverflow.com/questions/13056683/html-attribute-with-without-quotes – doctorlove Nov 10 '16 at 09:37
  • `workthreadcnt=1` is not valid XML – Christophe Roussy Nov 10 '16 at 09:38
  • Thank you all, I also think Attribute values in XML should be quoted. But in c++ tinyxml, there is a function like: const char* Attribute( const char* name, int* i ) const.It worked on my XML file. So I want to find a similar method in python. – David.Zhou Nov 10 '16 at 09:43
  • So that function takes an attribute name and an integer and returns a string - possibly the attribute with the value in quotes? – doctorlove Nov 10 '16 at 09:46
  • That function can parse the workthreadcnt=1, the value-result param i return the value of attribute directly. – David.Zhou Nov 10 '16 at 09:53
  • If you look at the comment in the tinyxml code here https://sourceforge.net/p/tinyxml/git/ci/master/tree/tinyxmlparser.cpp#l1443 you will see that the author has relaxed the requirement for quotes around attribute values. However this is rarely the case for most any other xml parser since it is not valid xml – Richard Nov 10 '16 at 10:01
  • 1
    Well, then I have to make my XML file well-formed. – David.Zhou Nov 10 '16 at 10:07
  • That is best. Note that python will treat strings that look like numbers as numbers for appropriate expressions, so it shouldn't cost you any complication. – Richard Nov 10 '16 at 10:09

0 Answers0