Domanda

Come posso leggere un file XML con Python elementtree, se l'XML ha più elementi di primo livello?

Ho un file XML che vorrei leggere utilizzando Python ElementTree.

Purtroppo, ha più tag di primo livello. Vorrei avvolgere intorno al <doc>...</doc> XML, tranne che devo mettere la <doc> dopo campi il <?xml> e <!DOCTYPE>. Ma per capire dove finisce <!DOCTYPE> non è banale.

Quello che ho:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE FOO BAR "foo.dtd" [
<!ENTITY ...>
<!ENTITY ...>
<!ENTITY ...>
]>
<ARTICLE> ... </ARTICLE>
<ARTICLE> ... </ARTICLE>
<ARTICLE> ... </ARTICLE>
<ARTICLE> ... </ARTICLE>

Quello che voglio:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE FOO BAR "foo.dtd" [
<!ENTITY ...>
<!ENTITY ...>
<!ENTITY ...>
]>
<DOC>
<ARTICLE> ... </ARTICLE>
<ARTICLE> ... </ARTICLE>
<ARTICLE> ... </ARTICLE>
<ARTICLE> ... </ARTICLE>
</DOC>

NB il nome di tag articolo potrebbe cambiare, quindi non posso grep per esso.

Qualcuno può suggerire a me come posso aggiungere la <doc>...</doc> racchiude dopo l'intestazione XML, o suggerire un'altra soluzione?

È stato utile?

Soluzione

ho scritto la seguente funzione per aggiungere un tag toplevel dopo le istruzioni di elaborazione XML. Ora è possibile trovare questo codice nel mio comune libreria Python come common.myelementtree.add_toplevel_tag

import re
xmlprocre = re.compile("(\s*<[\?\!])")
def add_toplevel_tag(string):
    """
After all the XML processing instructions, add an enclosing top-level <DOC> tag, and return it.
e.g.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <ARTICLE> ...
</ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE>
=>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]><DOC> <ARTICLE> ...
</ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE></DOC>
"""
    def _advance_proc(string, idx):
        # If possible, advance over whitespace and one processing
        # instruction starting at string index idx, and return its index.
        # If not possible, return None
        # Find the beginning of the processing instruction
        m = xmlprocre.match(string[idx:])
        if m is None: return None
        #print "Group", m.group(1)
        idx = idx + len(m.group(1))
        #print "Remain", string[idx:]

        # Find closing > bracket
        bracketdebt = 1
        while bracketdebt > 0:
            if string[idx] == "<": bracketdebt += 1
            elif string[idx] == ">": bracketdebt -= 1
            idx += 1
        #print "Remain", string[idx:]
        return idx
    loc = 0
    while 1:
        # Advance one processing instruction
        newloc = _advance_proc(string, loc)
        if newloc is None: break
        else: loc = newloc
    return string[:loc] + "<DOC>" + string[loc:] + "</DOC>"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top