Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python ElementTree在另一个xml文件的节点中插入一个xml文件_Python_Xml - Fatal编程技术网

使用Python ElementTree在另一个xml文件的节点中插入一个xml文件

使用Python ElementTree在另一个xml文件的节点中插入一个xml文件,python,xml,Python,Xml,我有两个xml文件,其中A引用了B。我想用Python将它们组合成一个xml文件 FileA.xml <FileAServices> <Services ref="FileB.xml" xpath="Services"/> </FileAServices> 只需使用elem.clear()和elem.append(…) 从io导入StringIO,字节io 将xml.etree.

我有两个xml文件,其中A引用了B。我想用Python将它们组合成一个xml文件

FileA.xml

    <FileAServices>
            <Services ref="FileB.xml" xpath="Services"/>
    </FileAServices>
只需使用
elem.clear()
elem.append(…)

从io导入StringIO,字节io
将xml.etree.ElementTree作为ET导入
a=b''\
\
'''
b=b''\
文件任务
\
'''
base=ET.parse(BytesIO(a))
ref=ET.parse(BytesIO(b))
root=base.getroot()
subroot=ref.getroot()
elem=root.find('Services')
元素清除()
对于subroot.iter('ThreadName')中的子元素:
元素附加(子元素)
out=BytesIO()
写(写出“UTF-8”)
打印(out.getvalue().decode('UTF8'))

先生,你帮我省了几个小时。向你致敬!
    <Services>
            <ThreadName>FileBTask</ChangeRequestName>
    </Services>
    <FileAServices>
         <Services>
                 <ThreadName>FileBTask</ThreadName>
         </Services>
    </FileAServices>
import xml.etree.ElementTree as ET
base = ET.parse('FileA.xml')
ref = ET.parse('FileB.xml')
root = base.getroot()
subroot = ref.getroot()
for elem in root.iter('Services'):
    elem.attrib = {}
    for subelem in subroot.iter():
        subdata = ET.SubElement(elem, subelem.text)
        if subelem.attrib:
            for k, v in subelem.attrib.items():
                subdata.set(k, v)