规范化Python minidom中的XML文本节点

2024-10-06 12:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想插入这个字符串:

No, on the 5<Font Script="super">th</Font>

作为XML中的文本节点xml.dom.minidomcreateTextNode(),但是,在我将writexml()写入一个文件后,会标记:

^{pr2}$

转向:

No, on the 5&lt;Font Script=&quot;super&quot;&gt;th&lt;/Font&gt;

我怎样才能避免这种情况?谢谢。在

我的代码的一部分:

impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, None, None)
TextTextNode = dom.createTextNode(text.decode("utf-8"))
Text = dom.createElement("Text")
Text.appendChild(TextTextNode)
fileToWrite =  codecs.open(output, 'w', encoding='utf-8')
dom.writexml(fileToWrite, indent=" ", addindent=" ", newl="\n", encoding='utf-8')
fileToWrite.close() 

cinecanvase规范中有一个示例:

<Text HAlign=”left” HPosition=”10.2” VAlign=”bottom” VPosition=”10.0”> This <Font Script=”super”>word </Font>is superscript </Text > 

我需要将<Font>..</Font>插入另一个元素中。在


Tags: thenotextltnoneonscriptdom
1条回答
网友
1楼 · 发布于 2024-10-06 12:30:31

我不熟悉这种格式,但它看起来像一个XML节点。试试这个:

from xml.dom import minidom
import codecs

output = "test.xml"
text="No, on the 5"


impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, None, None)
FontNode = dom.createElement("Font")
FontNode.setAttribute('Script', 'super')
FontNode.appendChild(dom.createTextNode('th'))
Text = dom.createElement("Text")
TextTextNode = dom.createTextNode(text.decode("utf-8"))
Text.appendChild(TextTextNode)
Text.appendChild(FontNode)
fileToWrite =  codecs.open(output, 'w', encoding='utf-8')
Text.writexml(fileToWrite, indent=" ", addindent=" ", newl="\n")
fileToWrite.close() 

结果是:

^{pr2}$

请注意,要在文件中编写树的内容(当调用writexml)时,需要使用XML的树根调用writexml方法(使用dom调用该方法,而不是使用根节点)

相关问题 更多 >