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
更多推荐
发布评论