[英]Python 2 xml.dom - Changing Element Prefix
我正在為舊版系統使用舊版本的Python(2.3),並且沒有可用的ElementTree(從2.5開始……)。 xml.dom
軟件包似乎是解析和編輯XML文檔的最佳接口,但是如果您發現此處不可行或存在明顯錯誤,請隨時引導我。
我無法更改已解析的XML。 我想將所有標簽設置為具有特定的前綴 / namespace,因此我編寫了以下函數:
def recursive_set_ns(root):
# type: (Element) -> None
"""Set namespaces for all tags recursively by DFS."""
if (root.prefix is None) or (root.prefix == ""):
root.prefix = "some_prefix"
if not root.hasChildNodes():
# Probably not necessary, though good to have for logic.
return
for child_tag in root.childNodes:
recursive_set_ns(child_tag)
由於某種原因,變量root.prefix
實際上確實會更新,但是當我使用document.toxml
或document.writexml
其打印出來時,此更改未反映在XML文檔中。
為了給出實際的MCVF,我認為這足以顯示我遇到的問題:
from xml.dom import minidom
document_string = "<atag>Some text.</atag>"
document = minidom.parseString(document_string)
# documentElement is the "atag" object here.
document.documentElement.prefix = "pre"
# Expecting to see "<pre:atag>Some text.</pre:atag>"
print(document.toxml()) # instead prints the original document_string
您可以在此處進行演示。 先感謝您!
我能夠自我回答。
element.tagName = "pre:" + element.tagName
顯然,只編輯整個標記是有效的,所以我這樣做了,而不是試圖找到一個對我有用的API調用。 花了很多時間在文檔上才能弄清楚這一點。 現在,我更改所有代碼的代碼如下:
def recursive_set_ns(root):
# type: (Element) -> None
"""Set namespaces for all tags recursively by DFS."""
if ":" not in root.tagName: # leave existing namespaces alone
root.tagName = "pre:" + root.tagName
children = filter(lambda c: c.nodeType == c.ELEMENT_NODE, root.childNodes)
for child_tag in children:
recursive_set_ns(child_tag)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.