gpt4 book ai didi

python - 如何通过 python 从不同的 XML 文件中获取元素来创建一个新文件?

转载 作者:太空宇宙 更新时间:2023-11-03 19:29:46 24 4
gpt4 key购买 nike

我有两个 xml 文件:

1.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

2.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

我需要创建一个新的 xml 文件 3.xml,其中包含 1.xml 和 2.xml 中的内容,如下所示:3.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</root>

我正在使用 Python ElementTree 模块解析 1.xml 和 2.xml,然后创建一个新文件。但它给了我错误:TypeError: 无法序列化(类型 Element)我正在使用的代码是:

from xml.etree import ElementTree as ET
#Tree for 1.xml
tree = ET.parse('1.xml')
root = tree.getroot()
Bookstore = root.find('bookstore')
#Tree for 2.xml
tree2 = ET.parse('2.xml')
root2 = tree2.getroot()
#3.xml
root_element = ET.Element("root")
child = ET.SubElement(root_element,Bookstore)
child = ET.SubElement(root_element,root2)
tree = ET.ElementTree(root_element)
tree.write("3.xml")

当我运行这个程序时,在写入 3.xml 时,它在最后给出“无法序列化”错误

最佳答案

SubElement 函数需要标记名称(文本字符串)作为第二个参数,而不是元素。不要调用 SubElement,而是尝试 append。脚本的最后一部分应该是:

#3.xml
root_element = ET.Element("root")
root_element.append(Bookstore)
root_element.append(root2)
tree = ET.ElementTree(root_element)
tree.write("3.xml")

关于python - 如何通过 python 从不同的 XML 文件中获取元素来创建一个新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6501512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com