0
votes

I want to insert this string:

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

as a Text Node in XML by xml.dom.minidom createTextNode(), however, after I writexml() to a file, the signs:

< > "

turns to:

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

How can I avoid this? Thanks.

A part of my code:

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() 

There is a sample for this by the cinecanvase specification:

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

I need insert the <Font>..</Font> into another element, the .

1
Is the 'Font' thing supposed to be an XML attribute? Could you post a complete XML sample of what you want to get? (verified using: w3schools.com/xml/xml_validator.asp ) - BorrajaX
@BorrajaX actually, it is a digital cinema subtitle xml standard, its specification is here: dlp.com/downloads/pdf_dlp_cinema_cinecanvas_rev_c.pdf , and the sample for that is like: <Text HAlign=”left” HPosition=”10.2” VAlign=”bottom” VPosition=”10.0”> This <Font Script=”super”>word </Font>is superscript </Text > - Liao Zhuodi
I find the answer from this post: stackoverflow.com/questions/1623607/… - Liao Zhuodi

1 Answers

1
votes

I'm not familiar with that format, but that thing looks like an XML node. Try this:

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() 

That outputs:

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

Be aware that what you want to write a tree in a file (when you call writexml) you need to call the writexml method with your XML's tree root (you were calling it with dom, not with your root node)