我有一個名為“test.xml”的 xml 檔案,格式如下
<final_output>
<career_profile>
<output>
<Template OriginalSentence="1" SentenceID="1" RecordID="0">
<Employer Type="String"><Value>HCL TECHNOLOGY LTD</Value></Employer>
<duration><Value>JAN 2018 to till date</Value></duration>
</Template>
</output>
</career_profile>
</final_output>
我想使用 python 在 test.xml 檔案之上添加一個 final_file 標簽。
輸出應如下所示:
<final_file>
<final_output>
<career_profile>
<output>
<Template OriginalSentence="1" SentenceID="1" RecordID="0">
<Employer Type="String"><Value>HCL TECHNOLOGY LTD</Value></Employer>
<duration><Value>JAN 2018 to till date</Value></duration>
</Template>
</output>
</career_profile>
</final_output>
</final_file>
為此,我使用了名為“random.xml”的附加 xml 檔案,其中包含 <final_file> </final_file> 。
random.xml 看起來像:
<final_file>
</final_file>
我沒有在生成的 output.xml 中得到 <final_output> </final_output> 標簽。
我嘗試了以下代碼:
import xml.etree.ElementTree as ET
xmlfile1 = "random.xml"
xmlfile2 = "test.xml"
tree1 = ET.parse(xmlfile1)
tree2 = ET.parse(xmlfile2)
root1 = tree1.getroot()
root2 = tree2.getroot()
root1.extend(root2)
tree1.write('output.xml')
但我越來越喜歡:
<final_file>
<career_profile>
<output>
<Template OriginalSentence="1" SentenceID="1" RecordID="0">
<Employer Type="String"><Value>HCL TECHNOLOGY LTD</Value></Employer>
<duration><Value>JAN 2018 to till date</Value></duration>
</Template>
</output>
</career_profile>
</final_file>
我試過
隨機.xml:
<final_file>
<final_output>
</final_output>
</final_file>
但我越來越像這樣:
<final_file>
<final_output> </final_output>
<career_profile>
<output>
<Template OriginalSentence="1" SentenceID="1" RecordID="0">
<Employer Type="String"><Value>HCL TECHNOLOGY LTD</Value></Employer>
<duration><Value>JAN 2018 to till date</Value></duration>
</Template>
</output>
</career_profile>
</final_file>
有沒有辦法在沒有額外的 random.xml 檔案的情況下做到這一點。
我期望的是,對于現有的 .xml 檔案,<finalfile*> 標記將被插入到檔案的頂部,</*final_file> 標記將被插入到檔案的底部。
uj5u.com熱心網友回復:
如果你想使用xmlpackage 那么簡單的解決方案就是
from xml.etree import ElementTree
xml_input = "input.xml"
xml_output = "output.xml"
tree_input = ElementTree.parse(xml_input)
root = tree_input.getroot()
# add new tag
new_root = ElementTree.Element("final_file")
new_root.insert(0, root)
# format XML
ElementTree.indent(new_root)
print(ElementTree.dump(new_root))
with open(xml_output, "wb") as xml_file:
xml_file.write(ElementTree.tostring(new_root))
在這種情況下,輸出將是
<final_file>
<final_output>
<career_profile>
<output>
<Template OriginalSentence="1" SentenceID="1" RecordID="0">
<Employer Type="String">
<Value>HCL TECHNOLOGY LTD</Value>
</Employer>
<duration>
<Value>JAN 2018 to till date</Value>
</duration>
</Template>
</output>
</career_profile>
</final_output>
</final_file>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536412.html
