python

超轻量级php框架startmvc

Python基于dom操作xml数据的方法示例

更新时间:2020-06-02 03:24 作者:startmvc
本文实例讲述了Python基于dom操作xml数据的方法。分享给大家供大家参考,具体如下:1、xml

本文实例讲述了Python基于dom操作xml数据的方法。分享给大家供大家参考,具体如下:

1、xml的内容为del.xml,如下


<?xml version="1.0" encoding="utf-8"?>
<catalog>
 <maxid>4</maxid>
 <login username="pytest" passwd='123456'>
 <caption>Python</caption>
 <item id="4">
 <caption>test</caption>
 </item>
 </login>
 <item id="2">
 <caption>Zope</caption>
 </item>
</catalog>

2、python的代码如下


# -*- coding:utf-8 -*-
#! python3
#1、获得标签属性
print("#1、获得标签属性")
import xml.dom.minidom
dom = xml.dom.minidom.parse("del.xml") #打开xml文档
root = dom.documentElement #得到xml文档
print("nodeName:",root.nodeName) #
print("nodeValue:",root.nodeValue)
print("nodeType:",root.nodeType)
print("ELEMENT_NODE:",root.ELEMENT_NODE)
#2、获得子标签
print("#2、获得子标签")
bb = root.getElementsByTagName('maxid')
print(type(bb))
print(bb)
b = bb[0]
print(b.nodeName)
print(b.nodeValue)
#3、获取标签属性值
print("#3、获取标签属性值")
itemlist = root.getElementsByTagName('login')
item =itemlist[0]
print(item.getAttribute("username"))
print(item.getAttribute("passwd"))
itemlist = root.getElementsByTagName('item')
item = itemlist[0] #通过在itemlist中的位置区分
print(item.getAttribute("id"))
item_1 = itemlist[1] #通过在itemlist中的位置区分
print(item_1.getAttribute("id"))
#4、获得标签对之间的数据
print("#4、获得标签对之间的数据")
itemlist1 = root.getElementsByTagName('caption')
item1 = itemlist1[0]
print(item1.firstChild.data)
item2 = itemlist1[1]
print(item2.firstChild.data)
#5总结
# minidom.parse(filename)
# 加载读取XML文件
#
# doc.documentElement
# 获取XML文档对象
#
# node.getAttribute(AttributeName)
# 获取XML节点属性值
#
# node.getElementsByTagName(TagName)
# 获取XML节点对象集合
#
# node.childNodes # 返回子节点列表。
#
# node.childNodes[index].nodeValue
# 获取XML节点值
#
# node.firstChild
# # 访问第一个节点。等价于pagexml.childNodes[0]

3、运行结果如下:

#1、获得标签属性 nodeName: catalog nodeValue: None nodeType: 1 ELEMENT_NODE: 1 #2、获得子标签 <class 'xml.dom.minicompat.NodeList'> [<DOM Element: maxid at 0x1dad800>] maxid None #3、获取标签属性值 pytest 123456 4 2 #4、获得标签对之间的数据 Python test

运行结果截图:

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具: http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XMLhttp://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具: http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具: http://tools.jb51.net/code/xmlcodeformat