我使用xml.etree.ElementTree来解析和修改一个utf-8XML文件。其中2个问题是因为文件是以Unix文件格式写入的,而不是Windows。问题1很明显,行尾是\n而不是\r\n。问题2是由于不同的文件格式(我假设),utf-8字符串的呈现方式不同。如何强制write()函数保存为Windows文件格式?我目前使用write()的方式如下:
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import sys
altSpellingTree = ET.parse(sys.argv[2])
altSpellingRoot = altSpellingTree.getroot()
recordList = altSpellingRoot.findall("record") # Grab all <record> elements and iterate
for record in recordList:
# Check for the existence of an <alternative_spelling> element
alt_spelling_node = record.find("person").find("names").find("alternative_spelling")
if alt_spelling_node == None:
continue
else:
# Check if <alternative_spelling> element text is solely ","
if alt_spelling_node.text == ",":
alt_spelling_node.text = None # Remove the lone comma
altSpellingTree.write(sys.argv[2], encoding="utf-8", xml_declaration=True)第三个问题是输出的文件使用了自结束标记,而以前有一个开始标记和一个结束标记(例如,<Country></Country>变成了<Country />)。有没有办法防止这种情况发生?
-编辑
下面是程序运行前XML的两个示例:
<Country></Country>
<Category_Type></Category_Type>
<Standard></Standard>
<names>
<first_name>Fernando</first_name>
<last_name>ROMERO AVILA</last_name>
<aliases>
<alias xsi:nil="true" />
</aliases>
<low_quality_aliases>
<alias xsi:nil="true" />
</low_quality_aliases>
<alternative_spelling>ROMERO ÁVILA,Fernando</alternative_spelling>
</names>和程序运行后相同的2个样本:
<Country />
<Category_Type />
<Standard />
<names>
<first_name>Fernando</first_name>
<last_name>ROMERO AVILA</last_name>
<aliases>
<alias xsi:nil="true" />
</aliases>
<low_quality_aliases>
<alias xsi:nil="true" />
</low_quality_aliases>
<alternative_spelling>ROMERO ÃVILA,Fernando</alternative_spelling>
</names>发布于 2014-10-22 22:00:51
我还没有测试你的代码是否有bug,但为了避免自动关闭标签,请更改以下代码:
altSpellingTree.write(sys.argv[2], encoding="utf-8", xml_declaration=True)至
altSpellingTree.write(sys.argv[2], encoding="utf-8", xml_declaration=True, method="html")应该能行得通。
为了大大简化您的代码,您可以使用iter来搜索树,如下所示:
import xml.etree.ElementTree as ET
tree = ET.parse('your.xml')
for el in tree.iter('alternative_spelling'):
# check your el text or whatever
if el.text == u",":
el.text = ""
print el.texthttps://stackoverflow.com/questions/26491025
复制相似问题