我想獲取 ElementTree 中某個元素的 xml 值。例如,如果我有代碼:
<?xml version="1.0" encoding="UTF-8"?>
<item>
<child>asd</child>
hello world
<ch>jkl</ch>
</item>
它會讓我
<child>asd</child>
hello world
<ch>jkl</ch>
到目前為止,這是我嘗試過的:
import xml.etree.ElementTree as ET
root = ET.fromstring("""<?xml version="1.0" encoding="UTF-8"?>
<item>
<child>asd</child>
hello world
<ch>jkl</ch>
</item>""")
print(root.text)
uj5u.com熱心網友回復:
嘗試
print(ET.tostring(root.find('.//child')).decode(),ET.tostring(root.find('.//ch')).decode())
或者,更具可讀性:
elems = ['child','ch']
for elem in elems:
print(ET.tostring(doc.find(f'.//{elem}')).decode())
基于您問題中的 xml 的輸出應該是您要查找的內容。
uj5u.com熱心網友回復:
基于Jack Fleeting 的回答,我創建了一個我認為更通用的解決方案,而不僅僅是與我插入的 xml 有關。
import xml.etree.ElementTree as ET
root = ET.fromstring("""<?xml version="1.0" encoding="UTF-8"?>
<item>
<child>asd</child>
hello world
<ch>jkl</ch>
</item>""")
for elem in root:
print(ET.tostring(root.find(f'.//{elem.tag}')).decode())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536422.html
標籤:PythonXML
