Python解析XML文件实现节点比对与转换的方法
本文介绍利用Python的xml.dom.minidom库处理XML文件的完整流程。通过解析RPD与CMAD格式的XML文件,提取节点值进行比对,并将匹配结果写入新的XML映射文件,未匹配的节点则单独输出。文章包含核心代码逻辑、节点结构说明及在线XML工具推荐,适用于需要自动化处理字符串资源或配置文件的开发者参考。
本文详细介绍使用Python操作XML文件的实用技巧,旨在为相关开发者提供清晰的实现思路与代码参考。
此前因工作需求,我深入学习了利用Python解析和处理XML文件的技术,现将具体实现方案整理如下,供同行交流探讨。
XML文件采用层级化的节点结构,由顶层的根节点向下逐层嵌套。例如:
<sys:String x:Key="STR_License_WithoutLicense">Sorry, you are not authorized.</sys:String>
在示例中,为节点名称,x:Key属性对应其值,而xml节点值则是的子节点,属于文本节点类型。其结构可概括为:<节点名称 x:Key="属性值">子节点内容…</节点名称>。
以下是RPD格式XML文件的示例:
<ResourceDictionary> <sys:String x:Key="STR_Startup_LaunchRPD">Launching Polycom RealPresence Desktop</sys:String> <sys:String x:Key="STR_Startup_CheckFolder">Checking folder</sys:String>
以下是CMAD格式XML文件的示例:
<language-strings> <ABK_CALL comment="verb (command, button on screen to press to place a call);" controls="Button" products="HDX,VSX,CMAD,Venus Main"> <ARABIC notes="" last-change-date="" status="">打电话</ARABIC> <CHINESE_S notes="" last-change-date="" status="">呼叫</CHINESE_S>
该段代码主要实现以下功能:
从RPD文件的String节点中提取节点值,并在CMAD文件的String节点中检索该值是否已存在。若存在,则返回CMAD中对应String的NodeName(节点名),并将这两个节点名分别作为新XML文件的节点名和节点值写入;若不存在,则将RPD中的该节点写入另一个独立的XML文件。具体代码如下:
import xml.dom.minidom
from xml.dom.minidom import Document
RPD_Str_path = "E:/PythonCode/StringResource.en-US.xaml"
RPD_dom = xml.dom.minidom.parse(RPD_Str_path)
CMAD_Str_path = "E:/PythonCode/M500_RPM13_0522.xml"
CMAD_dom = xml.dom.minidom.parse(CMAD_Str_path)
#得到根节点
RPD_root = RPD_dom.documentElement
CMAD_root = CMAD_dom.documentElement
def IsStr_already_Translated(RPD_Str):
for firstLevel in CMAD_root.childNodes:
for SecondLevel in firstLevel.childNodes:
if SecondLevel.nodeType == SecondLevel.ELEMENT_NODE:
if SecondLevel.nodeName == "ENGLISH_US":
if RPD_Str == SecondLevel.childNodes[0].data.strip():
return firstLevel.nodeName
else:
continue
else:
continue
else:
continue
else:
continue
else:
return "Null"
#用Document来写xml文件
Mapping_doc = Document()
Mapping_root = Mapping_doc.createElement("Common_String")
Mapping_doc.appendChild(Mapping_root)
Translation_doc = Document()
Translation_root = Translation_doc.createElement("Need_Translation_String")
Translation_doc.appendChild(Translation_root)
for node in RPD_root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
# print node.getAttribute("x:Key") +" + "+ node.childNodes[0].data
CMAD_Key = IsStr_already_Translated(node.childNodes[0].data.strip())
if(CMAD_Key != "Null"):
mKey = Mapping_doc.createElement(node.getAttribute("x:Key"))
Mapping_root.appendChild(mKey)
mValue = Mapping_doc.createTextNode(CMAD_Key)
mKey.appendChild(mValue)
elif(CMAD_Key == "Null"):
Key = Translation_doc.createElement('sys:String')
Translation_root.appendChild(Key)
Key.setAttribute('x:Key', node.getAttribute("x:Key"))
Value = Translation_doc.createTextNode(node.childNodes[0].nodeValue)
Key.appendChild(Value)
continue
else:
path1 = "E:/PythonCode/ID_Mapping.xml"
try:
import codecs
f1 = codecs.open(path1, "wb", "utf-8")
f1.write(Mapping_doc.toprettyxml(indent=" "))
except:
print('Write xml file failed.... file:{0}'.format(path1))
path2 = "E:/PythonCode/Need_Translate_String.xml"
try:
f2 = codecs.open(path2, "wb", "utf-8")
f2.write(Translation_doc.toprettyxml(indent=" "))
except:
print('Write xml file failed.... file:{0}'.format(path2))
此外,这里推荐几款实用的在线XML操作工具,供读者参考使用:
在线XML与JSON互转工具: http://tools.jb51.net/code/xmljson
在线XML格式化与压缩工具: http://tools.jb51.net/code/xmlformat
XML在线压缩及格式化工具: http://tools.jb51.net/code/xml_format_compress
XML代码在线格式化与美化工具: http://tools.jb51.net/code/xmlcodeformat
如需了解更多Python相关知识,可查阅本站专题:《Python操作xml数据技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。
希望本文提供的Python程序设计内容能对大家有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













