python - sorting strings via xml attribute, .text malforms xml data
<pre><code>#!/usr/bin/env python
import os, sys, os.path
import string 

def sort_strings_file(xmlfile,typee):
    """sort all strings within given strings.xml file"""

    all_strings = {}
    orig_type=typee

    # read original file
    tree = ET.ElementTree()
    tree.parse(xmlfile)

    # iter over all strings, stick them into dictionary
    for element in list(tree.getroot()):
        all_strings[element.attrib['name']] = element.text

    # create new root element and add all strings sorted below
    newroot = ET.Element("resources")
    for key in sorted(all_strings.keys()):
        # Check for IDs
        if typee == "id":
            typee="item"

        # set main node type
        newstring = ET.SubElement(newroot, typee)

        #add id attrib
        if orig_type == "id":
            newstring.attrib['type']="id"

        # continue on
        newstring.attrib['name'] = key
        newstring.text = all_strings[key]


    # write new root element back to xml file
    newtree = ET.ElementTree(newroot)
    newtree.write(xmlfile, encoding="UTF-8")
</code></pre>

<p>This works great and all, but if a string start with like <code>&lt;b&gt;</code> it breaks badly.
EX</p>

<pre><code>&lt;string name="uploading_to"&gt;&lt;b&gt;%s&lt;/b&gt; Odovzdávanie do&lt;/string&gt;
</code></pre>

<p>becomes</p>

<pre><code>&lt;string name="uploading_to" /&gt;
</code></pre>

<p>I've looked into the xml.etree Element class, but it seems to only have .text method. I just need a way to pull everything in between xml tags. No, I can't change the input data. It comes directly from an Android APK ready to be translated, I cannot predict how / what the data comes in besides the fact that it must be valid XML Android code.</p>
