我正在嘗試使用 Python 的 xml.etree.ElementTree 將 XML 樹寫入磁盤以重現給我的示例檔案。目標 XML 檔案中包含如下所示的欄位:
<title>
This is a test of <br/> Hershey's <sup>&$174;</sup> chocolate factory machine <br/>
</title>
我的問題是,每當我嘗試使用 ElementTree 的.write()方法將文本寫入磁盤時,我都無法實作上述輸出。html 標簽將被轉換為<br>或商標符號(? 東西)將顯示為實際符號。有沒有辦法對我的文本進行編碼以獲得上述輸出(其中商標由 ? 字符表示,但 html 是 html?)。我在 write 方法中嘗試了不同的編碼選項,但似乎沒有任何效果。
編輯:這是一個最小的作業示例。以輸入 XML 模板檔案為例:
<?xml version='1.0' encoding='UTF-8'?>
<document>
<title> Text to replace </title>
</document>
我們嘗試像這樣修改文本
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
to_sub_text = "This is a test of <br/> Hershey's <sup>&$174;</sup> chocolate factory machine"
spot = root.find('title')
spot.text = to_sub_text
tree.write('example_mod.xml', encoding='UTF-8', xml_declaration=True)
這將寫入檔案檔案:
<?xml version='1.0' encoding='UTF-8'?>
<document>
<title>This is a test of <br/> Hershey's <sup>&$174;</sup> chocolate factory machine</title>
</document>
正如我所說,我試圖復制的檔案將那些 html 標簽作為標簽。我的問題是:
- 我可以修改我的代碼來做到這一點嗎?
- 這樣做是好的做法,還是保持現狀會更好(因此我需要與團隊交談,要求我以這種方式向他們提供)?
uj5u.com熱心網友回復:
該spot.text = to_sub_text分配不作業。元素的text屬性僅包含純文本。不能使用它來添加文本和子元素。
您可以做的是創建一個新的<title>元素物件并將其附加到根:
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
# Remove the old title element
old_title = root.find('title')
root.remove(old_title)
# Add a new title
new_title = "<title>This is a test of <br/> Hershey's <sup>®</sup> chocolate factory machine</title>"
root.append(ET.fromstring(new_title))
# Prettify output (requires Python 3.9)
ET.indent(tree)
# Use encoding='US-ASCII' to force output of character references for non-ASCII characters
tree.write('example_mod.xml', encoding='US-ASCII', xml_declaration=True)
example_mod.xml 中的輸出:
<?xml version='1.0' encoding='US-ASCII'?>
<document>
<title>This is a test of <br /> Hershey's <sup>®</sup> chocolate factory machine</title>
</document>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/337089.html
上一篇:在XML檔案中搜索值串列
