Note that there are some explanatory texts on larger screens.

plurals
  1. POPython minidom/xml : How to set node text with minidom api
    primarykey
    data
    text
    <p>I am currently trying to load an xml file and modify the text inside a pair of xml tags, like this:</p> <pre><code> &lt;anode&gt;sometext&lt;/anode&gt; </code></pre> <p>I currently have a helper function called <code>getText</code> that I use to get the text <code>sometext</code> above. Now I need to modify the <code>childnodes</code> I guess, inside the node to modify a node that has the XML snippet shown above, to change <code>sometext</code> to <code>othertext</code>. The common API patch <code>getText</code> function is shown below in the footnote. </p> <p>So my question is, that's how we get the text, how do I write a companion helper function called <code>setText(node,'newtext')</code>. I'd prefer if it operated on the node level, and found its way down to the childnodes all on its own, and worked robustly.</p> <p>A previous question has an accepted answer that says "<a href="https://stackoverflow.com/questions/8076928/python-minidom-change-value-of-node">I'm not sure you can modify the DOM in place</a>". Is that really true? Is Minidom so broken that it's effectively Read Only?</p> <hr> <p>By way of footnote, to read text between <code>&lt;anode&gt;</code> and <code>&lt;/anode&gt;</code>, I took was surprised no direct simple single minidom function exists, and that this small helper function is suggested in the Python xml tutorials:</p> <pre><code>import xml.dom.minidom def getText(nodelist): rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc) # I've added this bit to make usage of the above clearer def getTextFromNode(node): return getText(node.childNodes) </code></pre> <p><a href="https://stackoverflow.com/questions/317413/get-element-value-with-minidom-python">Elsewhere</a> in StackOverflow, I see this accepted answer from 2008:</p> <pre><code> node[0].firstChild.nodeValue </code></pre> <p>If that's how hard it is to read with minidom, I'm not suprised to see that people say "Just don't do it!" when you ask how to write things that might modify the Node structure of your XML document.</p> <p><strong>Update</strong> The answer below shows it's not as hard as I thought.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload