2010-03-06 135 views
1

我有以下代码。Python XML需要编程错误帮助

import xml.dom.minidom 

def get_a_document(name): 
    return xml.dom.minidom.parse(name) 

doc = get_a_document("sources.xml") 

sources = doc.childNodes[1] 

for e in sources.childNodes: 
    if e.nodeType == e.ELEMENT_NODE and e.localName == "source": 
      for source in e.childNodes: 
        print source.localName 
        print source.nodeType 
        if source.nodeType == source.ELEMENT_NAME and source.localName == "language": 
          print source.localName 
      country = doc.createElement("country") 
      e.appendChild(country) 

我想读取sources.xml并添加一个元素国家。但是,我得到了以下错误。

AttributeError: Text instance has no attribute 'ELEMENT_NAME' 

sources.xml中看起来是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<!--sources.xml for multilingual, follows an ID range for different type of sources. Dailies sources are merged to this list--> 
    <sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <source> 
    <id>1005001</id> 
    <language>Afar</language> 
    <status>active</status> 
    <tags> 
     <tag>language</tag> 
    </tags> 
    <title>Afar</title> 
    </source> 
    </sources> 

可有人还建议为minidom命名库一个很好的教程。另外,如果你可以建议一个更好的python xml库,它会很棒。

感谢 巴拉

回答

1

什么是可能发生的事情是,你正在运行到包含您的标签之间的空白节点。目前尚不清楚你想要做什么,但如果你只是删除source.nodeType == source.ELEMENT_NAME部分,它可能会起作用。

1

[DOM文本节点 “U '的\ n'”,DOM元素:源在0x709f80,DOM文本节点 “U '的\ n'”]

每一个新的线被作为一个单独的儿童实体处理使用时xml.dom.minidom库。不幸的是,这些新行不包含值e.ELEMENT_NAME的值。看来你已经意识到这一点,但最终的问题是,你意味着它是e.ELEMENT_NODE不e.ELEMENT_NAME

for e in sources.childNodes: 
if e.nodeType == e.ELEMENT_NODE and e.localName == "source": 
     for source in e.childNodes: 
       if source.nodeType == e.ELEMENT_NODE and source.localName == "language": 
         print source.localName 
         print source.nodeType 
         print source.localName 
     country = doc.createElement("country") 
     e.appendChild(country) 

干杯, [R