給定 XML 檔案的以下結構:
<root>
<parent attr1="foo" attr2="bar">
<child> something </child>
</parent>
.
.
.
如何將屬性從父元素傳遞到子元素并洗掉父元素以獲得以下結構:
<root>
<child attr1="foo" attr2="bar">
something
</child>
.
.
.
uj5u.com熱心網友回復:
好吧,您需要查找<parent>,然后查找,從to<child>復制屬性,附加到根節點并洗掉。一切就是這么簡單:<parent><child><child><parent>
import xml.etree.ElementTree as ET
xml = '''<root>
<parent attr1="foo" attr2="bar">
<child> something </child>
</parent>
</root>'''
root = ET.fromstring(xml)
parent = root.find("parent")
child = parent.find("child")
child.attrib = parent.attrib
root.append(child)
root.remove(parent)
# next code is just to print patched XML
ET.indent(root)
ET.dump(root)
結果:
<root>
<child attr1="foo" attr2="bar"> something </child>
</root>
你可以幫助我的國家,查看我的個人資料資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/447873.html
上一篇:從Groovy主動選擇反應參考引數中的JSON串列回傳子串列
下一篇:讀取XMLCLOB列中的標簽
