python 使用DOM读取xml




#http://www.runoob.com/python3/python3-xml-processing.html点击打开链
#!/usr/bin/python3

from xml.dom.minidom import parse
import xml.dom.minidom

document = xml.dom.minidom.parse("movies.xml")
collection = document.documentElement
if collection.hasAttribute("shelf"):
    print("Root element: %s" % collection.getAttribute("shelf"))

movies = collection.getElementsByTagName("movie")

for movie in movies:
    print("=====Movie=====")
    if movie.hasAttribute("title"):
        print("Title: %s" % movie.getAttribute("title"))

    type = movie.getElementsByTagName('type')[0]
    print("Type: %s" % type.childNodes[0].data)
    format = movie.getElementsByTagName('format')[0]
    print("Format: %s" % format.childNodes[0].data)
    rating = movie.getElementsByTagName('rating')[0]
    print("Rating: %s" % rating.childNodes[0].data)
    description = movie.getElementsByTagName('description')[0]
    print("Description: %s" % description.childNodes[0].data)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Python的`xml.dom.minidom`模块可以用DOM方式解析XML文件,并操作XML节点。下面是一个使用DOMXML特定字段进行排序的示例代码: ```python import xml.dom.minidom # 解析XML文件 doc = xml.dom.minidom.parse('example.xml') root = doc.documentElement # 选择要排序的字段 items = root.getElementsByTagName('item') # 根据特定属性进行排序 items = sorted(items, key=lambda item: item.getAttribute('name')) # 创建新的XML节点,按照排序结果添加子节点 new_root = doc.createElement('root') for item in items: new_root.appendChild(item) # 将新的XML节点添加到文档中 doc.removeChild(root) doc.appendChild(new_root) # 保存文档 with open('sorted.xml', 'w', encoding='utf-8') as f: f.write(doc.toprettyxml(indent='\t', encoding='utf-8').decode('utf-8')) ``` 在上面的例子中,我们首先使用`xml.dom.minidom.parse`方法解析XML文件,并获取根节点。然后,使用`root.getElementsByTagName`方法选择要排序的字段。在本例中,我们选择了所有名为`item`的元素。接下来,使用Python的`sorted`方法和`lambda`函数根据`name`属性对选定的元素进行排序。接着,我们创建一个新的XML节点,并按照排序结果添加子节点。最后,将新的XML节点添加到文档中,并保存到文件中。 请注意,上述代码仅适用于简单的XML文件。如果您的XML文件比较复杂,您可能需要使用Python的`xml.etree.ElementTree`模块或第三方库来解析和操作XML文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值