如何通过python从一个xml中提取多个xml节(how to extract section to multiple xml from one xml via python)

编程入门 行业动态 更新时间:2024-10-25 06:33:03
如何通过python从一个xml中提取多个xml节(how to extract section to multiple xml from one xml via python)

source.xml

<root xxx> <test> <ppp> <ppp> xxx </ppp> <ppp> yyy </ppp> ... ... </ppp> </test>

ppp中有很多我想将它提取到单个文件:

1.XML:

<ppp> xxx </ppp>

2.XML

<ppp> yyy </ppp>

3.xml等

我知道它可以通过xml.etree.ElementTree来实现请给我一个例子,令人困惑的部分是它有双ppp。

source.xml

<root xxx> <test> <ppp> <ppp> xxx </ppp> <ppp> yyy </ppp> ... ... </ppp> </test>

there are many among ppp I want to extract it to single files :

1.xml:

<ppp> xxx </ppp>

2.xml

<ppp> yyy </ppp>

3.xml and so on

I know it can be achieved by xml.etree.ElementTree pls kindly give me an example for this, the confusing part is it has double ppp.

最满意答案

使用xml.etree.ElementTree模块的解决方案:

import xml.etree.ElementTree as ET # to load xml contents from file use the following: # tree = ET.parse('source.xml') # root = tree.getroot() source = '''<?xml version="1.0"?> <root> <test> <ppp> <ppp> xxx </ppp> <ppp> yyy </ppp> </ppp> </test> </root> ''' root = ET.fromstring(source) for k, ppp in enumerate(root.findall('./test/ppp/ppp')): tree = ET.ElementTree(ppp) tree.write(str(k+1) + '.xml')

root.findall('./test/ppp/ppp') - 按路径查找所有匹配的元素

tree.write() - 将元素树作为XML写入文件

上面的代码将解析所需的元素并将它们分别写入1.xml和2.xml文件

https://docs.python.org/3/library/xml.etree.elementtree.html

The solution using xml.etree.ElementTree module:

import xml.etree.ElementTree as ET # to load xml contents from file use the following: # tree = ET.parse('source.xml') # root = tree.getroot() source = '''<?xml version="1.0"?> <root> <test> <ppp> <ppp> xxx </ppp> <ppp> yyy </ppp> </ppp> </test> </root> ''' root = ET.fromstring(source) for k, ppp in enumerate(root.findall('./test/ppp/ppp')): tree = ET.ElementTree(ppp) tree.write(str(k+1) + '.xml')

root.findall('./test/ppp/ppp') - finds all matching elements by path

tree.write() - writes the element tree to a file, as XML

The above code will parse the needed elements and write them into files 1.xml and 2.xml respectively

https://docs.python.org/3/library/xml.etree.elementtree.html

更多推荐

本文发布于:2023-08-06 14:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   xml   python   multiple   section

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!