编辑属性值并使用python在xml中添加新属性

时间:2018-02-13 13:18:07

标签: python xml

以下是包含3个数据源的示例XML文件。在每个数据源中都有一个具有属性的标记。

现在,在3个数据源中,其中2个没有属性,其中一个数据源有,但值为false。

我想在缺少的属性中添加属性,并在数据源中将其值修改为true。

SAMPLE XML代码段

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

使用DOM

# import minidom
import xml.dom.minidom as mdom

# open with minidom parser
DOMtree = mdom.parse("Input.xml")
data_set = DOMtree.documentElement

# get all validation elements from data_Set
validations = data_set.getElementsByTagName("validation")

# read all validation from validations
for validation in validations:
    # get the element by tag anme
    use-fast-fail = validation.getElementsByTagName('use-fast-fail')
    # if the tag exist
    if use-fast-fail:
        if use-fast-fail[0].firstChild.nodeValue == "false":
            # if tag value is false replace with true
            use-fast-fail[0].firstChild.nodeValue = "true"
    # if tag does not exist add tag
    else:
        newTag = DOMtree.createElement("use-fast-fail")
        newTag.appendChild(DOMtree.createTextNode("true"))
        validation.appendChild(newTag)

# write into output file
with open("Output.xml", 'w') as output_xml:
   output_xml.write(DOMtree.toprettyxml())

使用正则表达式进行简单的文件读取和字符串搜索

# import regex
import re

#open the input file with "read" option
input_file = open("intput.xml", "r")
#put content into a list
contents = input_file.readlines()
#close the file
input_file.close()

#loop to check the file line by line
#for every entry - get the index and value
for index, value in enumerate(contents):
    #searches the "value" contains attribute with false value
    if (re.search('<background-validation>false<background-validation/>',value)):
        #if condition true True - changes to desired value
        contents[index] = "<background-validation>true<background-validation/>\n"
    #searches the "value" contains attribute, which always comes just before the desired attribute
    if (re.search('validate-on-match',value)):
        #searches the "value" of next element in the list contains attribute
        if not (re.search('<background-validation>"',contents[index + 1])):
            #if not adding the attribute
            contents.insert(index + 1, "<background-validation>true<background-validation/>\n")

#open the file with "write" option
output_file = open("Output.xml", "w")
#joining all contents
contents = "".join(contents)
#write into output file
output_file.write(contents)
output_file.close()

注意:在第二个选项中,假设所有数据源块的结构和顺序相同,则在不存在的情况下添加行,否则我们可能需要检查多个条件