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

2024-04-27 00:14:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个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文件

^{pr2}$

我需要创建一个新的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:cannot serialize(type 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时,它在结尾处给出“无法序列化”错误


Tags: 文件treelangtitlerootxmlelementyear
1条回答
网友
1楼 · 发布于 2024-04-27 00:14:12

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")

相关问题 更多 >