将XML标签插入另一个其他标签

时间:2019-03-11 20:06:49

标签: xml python-3.x elementtree

我试图用ElementTree遍历Python中的一个XML文件,更改标记中的一个属性,然后将该标记插入另一个文件中的另一个标记中,如下所示:

import xml.etree.ElementTree as ET

tree = ET.parse('original_file.xml')
root = tree.getroot()
cnt = 1


exact = ET.Element("eExact")
glentries = ET.SubElement(exact, "GLEntries")
glentry = ET.SubElement(glentries, "GLEntry", status="E", entry="194100751")

ET.SubElement(glentry, "DocumentDate").text = "31032019"
ET.SubElement(glentry, "Description").text = "TEST"

ET.SubElement(glentry, "Journal", code="41", type="M")

for child in root.iter('FinEntryLine'):
    child.attrib["number"] = cnt
    ET.SubElement(glentry, child)
    cnt += 1

tree = ET.ElementTree(exact)
tree.write("output_file.xml")

但是,这不起作用,因为ElemntTree和SubElement报告无法序列化。还有另一种方法,但是我不必遍历“子”的所有子标签吗?

输入文件:

<eExact>
   <GLEntries>
     <GLEntry status="E" entry="194100751">
       <DocumentDate>31032019</DocumentDate>
       <Description>TEST</Description>
       <Journal code="41" type="M"></Journal>

  <FinEntryLine number="83932" type="N" subtype="N">
    <Description>01032019 GWPC 1900005105</Description>
  </FinEntryLine>
  <FinEntryLine number="98457" type="N" subtype="N">
    <Description>01032019 GWPC 1900005105</Description>
  </FinEntryLine>

  </GLEntry>
  </GLEntries>
</eExact>

输出应仅将数字标签从1开始更改为顺序。

1 个答案:

答案 0 :(得分:1)

如果您只想更改number元素的<FinEntryLine>属性,这就是所有需要的内容:

import xml.etree.ElementTree as ET

tree = ET.parse('original_file.xml')
cnt = 1

for child in tree.iter('FinEntryLine'):
    child.attrib["number"] = str(cnt)
    cnt += 1

tree.write("output_file.xml")

结果(output_file.xml):

<eExact>
   <GLEntries>
     <GLEntry entry="194100751" status="E">
       <DocumentDate>31032019</DocumentDate>
       <Description>TEST</Description>
       <Journal code="41" type="M" />

  <FinEntryLine number="1" subtype="N" type="N">
    <Description>01032019 GWPC 1900005105</Description>
  </FinEntryLine>
  <FinEntryLine number="2" subtype="N" type="N">
    <Description>01032019 GWPC 1900005105</Description>
  </FinEntryLine>

  </GLEntry>
  </GLEntries>
</eExact>