1

环境:Python 2.6.5、Eclipse SDK 3.7.1、Pydev 2.3

我正在尝试使用 Python 解析和更改 XML 数据中的值,xml.dom.minidom但我遇到了空白文本节点的问题。

当我将 XML 文件解析为 DOM 对象,然后使用 将其转换回字符串toxml()时,在所有空白文本节点之后,结束的“描述”标签会变得混乱。

有谁知道问题是什么?

issue.py 的内容

from xml.dom import minidom  
xml_dom_object = minidom.parse('news_shows.xml')  
main_node = xml_dom_object.getElementsByTagName('NewsShows')[0]  
xml_string = main_node.toxml()  
print xml_string  

news_shows.xml的内容(注意两个空白文本节点)

<NewsShows Planet="Earth" Language="English" Year="2012">
<NewsShow ShowName="The_Young_Turks">
 <Description Detail="Best_show_of_all_time_according_to_many">True</Description>
 <Description Detail="The_only_source_of_truth"></Description>
 <Description Detail="Three_hours_of_truth_per_day">True</Description>
</NewsShow>
<NewsShow ShowName="The_Rachel_Maddow_Show">
<Description Detail="Pretty_great_as_well">True</Description>
<Description Detail="Sucks_badly">False</Description>
<Description Detail="Conveys_more_information_than_TYT"></Description>
</NewsShow>
</NewsShows>

脚本的输出(注意 2 个“描述”标签搞砸了)

<NewsShows Language="English" Planet="Earth" Year="2012">
<NewsShow ShowName="The_Young_Turks">
 <Description Detail="Best_show_of_all_time_according_to_many">True</Description>
 <Description Detail="The_only_source_of_truth"/>
 <Description Detail="Three_hours_of_truth_per_day">True</Description>
</NewsShow>
<NewsShow ShowName="The_Rachel_Maddow_Show">
<Description Detail="Pretty_great_as_well">True</Description>
<Description Detail="Sucks_badly">False</Description>
<Description Detail="Conveys_more_information_than_TYT"/>
</NewsShow>

4

2 回答 2

1

下面是来自“python-3.2.3.amd64\Lib\xml\dom\minidom.py”的代码片段。

def writexml(self, writer, indent="", addindent="", newl=""):
    # indent = current indentation
    # addindent = indentation to add to higher levels
    # newl = newline string
    writer.write(indent+"<" + self.tagName)

    attrs = self._get_attributes()
    a_names = sorted(attrs.keys())

    for a_name in a_names:
        writer.write(" %s=\"" % a_name)
        _write_data(writer, attrs[a_name].value)
        writer.write("\"")
    if self.childNodes:
        writer.write(">")
        if (len(self.childNodes) == 1 and
            self.childNodes[0].nodeType == Node.TEXT_NODE):
            self.childNodes[0].writexml(writer, '', '', '')
        else:
            writer.write(newl)
            for node in self.childNodes:
                node.writexml(writer, indent+addindent, addindent, newl)
            writer.write(indent)
        writer.write("</%s>%s" % (self.tagName, newl))
    else:
        writer.write("/>%s"%(newl))

根据该函数,如果“self”变量(即要写入XML 的节点)没有“childNodes”,则编写器将编写一个自关闭标签。

于 2012-07-12T02:29:23.767 回答
0

这实际上会在某处引起问题吗?根据我对 xml 的所有了解,字符串<tag></tag><tag/>是等价的。

于 2012-07-12T01:59:22.610 回答