Python XML需要关于编程错误的帮助
我有下面的代码Python XML需要关于编程错误的帮助,python,xml,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 == "s
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并添加一个元素country。但是,我得到了下面的错误
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>
1005001
远处
积极的
语言
远处
也有人能为minidom库推荐一个好的教程吗。另外,如果您能推荐一个更好的python xml库,那就太好了
谢谢
Bala可能发生的情况是,您正在运行包含标记之间空白的节点。不清楚您试图做什么,但如果您只删除
source.nodeType==source.ELEMENT\u NAME
部分,它可能会起作用。[DOM文本节点“u'\n',DOM元素:源代码0x709f80,DOM文本节点“u'\n']
在使用xml.dom.minidom库时,每个新行都被视为一个单独的子实体。不幸的是,这些新行不包含值e.ELEMENT\u NAME值。看起来您已经意识到了这一点,但最终的问题是您希望它是e.ELEMENT\u节点,而不是e.ELEMENT\u名称
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