开发者

Python XML need help with programming error

I am having the below code.

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)

I am trying to read the sources.xml and add an element country. But, I am getting the below error.

AttributeError: Text instance has no attribute 'ELEMENT_NAME'

Sources.xml looks like this:

<?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>

Can someone also suggest a good tutorial for minidom library. Al开发者_StackOverflow社区so, if you could suggest a better python xml library, it will be great.

Thanks Bala


What's probably happening is you're running into the nodes containing the whitespace between your tags. It's not clear what you're trying to do, but it might work if you just remove the source.nodeType == source.ELEMENT_NAME part.


[DOM Text node "u'\n '", DOM Element: source at 0x709f80, DOM Text node "u'\n '"]

Every new line is treated as a separate child entity when using the xml.dom.minidom library. Unfortunately, these new lines do not contain the value e.ELEMENT_NAME value. It seems that you have realized this, but the ultimate issue is that you meant for it to be e.ELEMENT_NODE not 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)

Cheers, R

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜