在多个XML文件中编辑多个XML节点

凯文

我有多个XML文件(60多个),需要编辑多个文本节点(我认为这被称为)。我熟悉Java,JavaScript,Python,JQuery,PHP,HTML。

我可以用什么语言来完成?

这是我当前拥有的样本XML文档的内容:

<?xml version="1.0" encoding="utf-8"?><bookstore>
    <book category="cooking">
        <title lang="en">Chinese</title>
        <author>chinese author</author>
        <year>2015</year>
        <price>fourth</price>
    </book>
    <book category="cooking">
        <title lang="en">All American</title>
        <author>American Author</author>
        <year>2015</year>
        <price>6.00</price>
    </book>
</bookstore>

因此,例如,我想一次更改多个元素的作者和年份!

这是我的python代码,它将一次编辑一个节点。我需要一个循环或一些东西来一次编辑更多内容。

from xml.dom.minidom import parse
import os

# create a backup of original file
new_file_name = 'dom.xml'
old_file_name = new_file_name + "~"
os.rename(new_file_name, old_file_name)

# change text value of element
doc = parse(old_file_name)
node = doc.getElementsByTagName('author')
node[0].firstChild.nodeValue = 'new author'


# persist changes to new file
xml_file = open(new_file_name, "w")
doc.writexml(xml_file, encoding="utf-8")
xml_file.close()

任何帮助将不胜感激。新手程序员在这里!

谢谢你!:D

布伦特·沃什伯恩

创建函数:

def create_backup(new_file_name):
    """ create a backup of original file """
    old_file_name = new_file_name + "~"
    os.rename(new_file_name, old_file_name)
    return old_file_name

def change_author(doc, new_author)
    """ change text value of 'author' """
    node = doc.getElementsByTagName('author')
    node[0].firstChild.nodeValue = new_author

def save_changes(new_file_name, doc):
    """ persist changes to new file """
    xml_file = open(new_file_name, "w")
    doc.writexml(xml_file, encoding="utf-8")
    xml_file.close()

现在很容易创建循环:

file_names = ['dom.xml', ...]
for new_file_name in file_names:
    old_file_name = create_backup(new_file_name)
    doc = parse(old_file_name)
    change_author(doc, 'new author')
    save_changes(new_file_name, doc)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章