问题
I am trying to add some sibling tags after <VIDPOM>10</VIDPOM>
tag
My XML looks like:
<ZAP>
<N_ZAP>999</N_ZAP>
<SLUCH>
<IDCASE>100100100</IDCASE>
<USL_OK>3</USL_OK>
<VIDPOM>10</VIDPOM>
<IDSP>99</IDSP>
<USL>
<IDSERV>123456789</IDSERV>
<DATE_IN>2020-12-01</DATE_IN>
</USL>
</SLUCH>
</ZAP>
But I want to make it like this:
<ZAP>
<N_ZAP>999</N_ZAP>
<SLUCH>
<IDCASE>100100100</IDCASE>
<USL_OK>3</USL_OK>
<VIDPOM>10</VIDPOM>
<MY_CUSTOM_TAG>TEXT IS HERE</MY_CUSTOM_TAG>
<IDSP>99</IDSP>
<USL>
<IDSERV>123456789</IDSERV>
<DATE_IN>2020-12-01</DATE_IN>
</USL>
</SLUCH>
</ZAP>
My code is:
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
for SLUCH in root.iter('SLUCH'):
IDCASE = SLUCH.find('IDCASE')
VIDPOM = SLUCH.find('VIDPOM')
print(IDCASE.text)
print(VIDPOM.text)
print()
if IDCASE.text == "100100100":
print('HERE')
new_tag = ET.SubElement(VIDPOM, 'MY_CUSTOM_TAG')
new_tag.text = 'TEXT IS HERE'
tree.write('file_new.xml')
The output is:
<ZAP>
<N_ZAP>999</N_ZAP>
<SLUCH>
<IDCASE>100100100</IDCASE>
<USL_OK>3</USL_OK>
<VIDPOM>10
<MY_CUSTOM_TAG>TEXT IS HERE</MY_CUSTOM_TAG>
</VIDPOM>
<IDSP>99</IDSP>
<USL>
<IDSERV>123456789</IDSERV>
<DATE_IN>2020-12-01</DATE_IN>
</USL>
</SLUCH>
</ZAP>
Thank you in advance!
回答1:
You can find position of VIDPOM
in list of children of SLUCH
index = list(SLUCH).index(VIDPOM) # deprecated: SLUCH.getchildren().index(VIDPOM)
and then you can insert
one position after VIDPOM
SLUCH.insert(index+1, new_tag)
To format new element like VIDPOM
(the same indentations) you can copy tail
new_tag.tail = VIDPOM.tail
Minimal working code - with data directly in code.
text ='''
<ZAP>
<N_ZAP>999</N_ZAP>
<SLUCH>
<IDCASE>100100100</IDCASE>
<USL_OK>3</USL_OK>
<VIDPOM>10</VIDPOM>
<IDSP>99</IDSP>
<USL>
<IDSERV>123456789</IDSERV>
<DATE_IN>2020-12-01</DATE_IN>
</USL>
</SLUCH>
</ZAP>
'''
import xml.etree.ElementTree as ET
#tree = ET.parse('file.xml')
#root = tree.getroot()
root = ET.fromstring(text)
for SLUCH in root.iter('SLUCH'):
VIDPOM = SLUCH.find('VIDPOM')
new_tag = ET.Element('MY_CUSTOM_TAG')
new_tag.text = 'TEXT IS HERE'
new_tag.tail = VIDPOM.tail # copy text after `tag`
index = list(SLUCH).index(VIDPOM)
#index = SLUCH.getchildren().index(VIDPOM) # deprecated
SLUCH.insert(index+1, new_tag)
print(ET.tostring(root).decode())
Result:
<ZAP>
<N_ZAP>999</N_ZAP>
<SLUCH>
<IDCASE>100100100</IDCASE>
<USL_OK>3</USL_OK>
<VIDPOM>10</VIDPOM>
<MY_CUSTOM_TAG>TEXT IS HERE</MY_CUSTOM_TAG>
<IDSP>99</IDSP>
<USL>
<IDSERV>123456789</IDSERV>
<DATE_IN>2020-12-01</DATE_IN>
</USL>
</SLUCH>
</ZAP>
来源:https://stackoverflow.com/questions/65523775/python-write-siblings-in-xml-below-desired-tag