python 学习笔记之minidom

上一篇 / 下一篇  2013-04-21 12:32:54

最近要用python写一个小的脚本,正好学习下python,期间要解析xml文件,发现minidom是一个轻量级的处理xml的库,顺便就记录下来

首先要用minidom package 就要import它

 

[python] view plaincopy
  1. from xml.dom import minidom  

搞定,现在我就能能使用他了,

读取xml

[python] view plaincopy
  1. doc = minidom.parse(file_name)  

这时候我们就拿到了xml的整个doc 树,下面的工作就很简单了

[python] view plaincopy
  1. root = doc.documentElement  
  2. node=root.getElementsByTagName('name')  

拿到node之后,我们就可以读取node的信息了

[python] view plaincopy
  1. node.getAttribute('id')  

[python] view plaincopy
  1. node.nodeName  
  2. node.nodeValue  
  3. node.childNodes  

在取node的attribute的时候要判断是否为minidom.Node.ELEMENT_NODE,因为parse后,所有两个标记间的内容都被视为文本结点。象每行后面的回车,都被看到文本结点

创建一个节点

[python] view plaincopy
  1. x = dom.createElement("foo")  # creates <foo />  
  2. dom.childNodes[1].appendChild(x)  # appends at end of 1st child's children  

打印xml

[python] view plaincopy
  1. print dom.toxml()  


写xml

[python] view plaincopy
  1. 79     f = codecs.open(file_name,'w','utf-8')  
  2. 80     dom.writexml(f, encoding='utf-8')  
  3. 81     f.close()  

大功告成。



本文出自“shadowwalker”博客http://www.51testing.com/?622454,转载请保留出处

TAG:

 

评分:0

我来说两句

日历

« 2024-05-02  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 12135
  • 日志数: 9
  • 建立时间: 2013-04-21
  • 更新时间: 2013-05-05

RSS订阅

Open Toolbar