我是Python新手,不知道从哪里开始解决问题。在
我需要做的是:从一个文件夹中读取一个XML文件,并将其拆分到多个XML文件中(在另一个文件夹中),涉及到一个特定的重复节点(用户将输入该节点),同时保留页眉(在该节点之前的内容)和页脚(节点之后的内容)。在
下面是一个例子:
<?xml version="1.0"?>
<catalog catalogName="cat1" catalogType="bestsellers">
<headerNode node="1">
<param1>value1</param1>
<param2>value2</param2>
</headerNode>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<footerNode node="2">
<param1>value1</param1>
<param2>value2</param2>
</footerNode>
</catalog>
因此,我们的目的是要有3个XML文件(因为我们有3个“book”节点实例)具有“headerNode”+1“book”+“footerNode”。在
第一个文件如下:
^{pr2}$唯一的限制是它需要使用“ElementTree”而不是“lxml”库来完成(因为lxml不包含在生产依赖项中)。在
编辑:这里是基于“MK Ultra”的答案的代码。在
现在我修改了它,将两个参数传递给脚本(第一个是不带扩展名的XML文件名,第二个是split节点),现在我读取XML并在与脚本相同的文件夹中生成XML文件。(我在循环中使用索引来命名文件夹)
import sys
import xml.etree.ElementTree as ET
import os
# Get the current directory
cwd = os.getcwd()
# Load the xml
doc = ET.parse(r"%s/%s.xml" % (cwd,sys.argv[1]))
root = doc.getroot()
# Get the header element
header = root.find("headerNode")
# Get the footer element
footer = root.find("footerNode")
# loop over the books and create the new xml file
for idx,book in enumerate(root.findall(sys.argv[2])):
top = ET.Element(root.tag)
top.append(header)
top.append(book)
top.append(footer)
out_book = ET.ElementTree(top)
# the output file name will be the ID of the book
out_path = "%s/%s_%s.xml" % (cwd,sys.argv[1],idx)
out_book.write(open(out_path, "wb"))
如何使“headerNode”/“footerNode”部分通用?我的意思是,它应该是“书”或其他类似“小说”、“纸张”之类的东西。正确的值只有脚本的用户(显然不是我)在运行它时才知道。在
EDIT2:刚刚修改了原始文件以将属性添加到“catalog”节点,因为创建拆分文件时无法复制属性。在
从我的头顶上你可以这样做:
算法如下:
样本输出:
文件名:bk101.xml
^{pr2}$编码快乐!在
相关问题 更多 >
编程相关推荐