【问题标题】:Python edit xml with minidomPython用minidom编辑xml
【发布时间】:2015-04-14 16:33:28
【问题描述】:

尽我所能,我只是没有让这个工作。我有一个 xml 文件:

我需要更改 xyz 的值并将名称添加到名称标签。我就是不知道怎么去那里。

我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from xml.dom import minidom
xmldoc = minidom.parse('example.xml')


sensorList = xmldoc.getElementsByTagName('sensor')

for sensor in sensorList:
    sensor.firstChild.nodeValue = "test"
    sensor.nextSibling.nodeValue # skip over
    sensor.nextSibling.nodeValue = "1"
    sensor.nextSibling.nodeValue = "2"
    sensor.nextSibling.nodeValue = "3"
    #print sensor.toxml()

xml_file_handle = open('example.xml' , 'wb')
xmldoc.writexml(xml_file_handle)
xml_file_handle.close()

我已经尝试了 sensor.childNodes[0].data 或 value 的几种变体。这将返回没有属性的错误。如果我使用 print sensor.toxml() 一切正常。

当我运行此代码时,我确实得到了要打印的测试,但它是在“传感器”标签之后插入的,而不是“名称”标签之后。我知道简单的语法问题,但我只是在文档中找不到它。

非常感谢您的帮助。

【问题讨论】:

    标签: python xml-parsing


    【解决方案1】:

    我找不到 minidom 的解决方案。

    我切换到 ElementTree 并且能够解决一个问题。 我实际需要做的是读取 .csv 文件并使用第二个文件中的值重写 xml,但与覆盖 xml 相比,这变得微不足道。

    以前的解决方案:

    #!/usr/bin/python
    
    import sys
    import xml.etree.ElementTree as ET
    xmlFile = sys.argv[1]
    
    # Xml parsing.
    tree = ET.parse(xmlFile)
    root = tree.getroot()
    
    #Access the nodes you want by treating root as an array of arrays
    # roots children = root[x]
    # roots children's children root[x][y]etc
    
    #The array of sensors
    sensors = root[1]
    
    for sensor in sensors:
    #Access all of sensors children the same way as root.
        sensor[0].text = 'test'
        sensor[3].text = '1'
        sensor[4].text = '2'
        sensor[5].text = '3'
    
    #Open the xmlfile and rewrite it.
    xmlFileHandle = open(xmlFile,'wb')
    xmlFileHandle.write('<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(root))
    xmlFileHandle.close()
    

    请注意,xml 样板的顶行需要手动替换。 此外,您需要创建一个自定义方法来清除前缀名称空间 或在处理和替换之前删除架构,具体取决于您的需要。有些人想要前缀。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2017-09-22
      • 2018-10-23
      相关资源
      最近更新 更多