How to prevent XMLSerializer.serializeToString () from changing attributes?

I use jQuery to load arbitrary XML strings (fragments of a larger document) into the browser DOM and manipulate them, and then use XMLSerializer to load them back into strings and send them back to the server where they are processed (python and lxml) and reintegrated into a complete XML document.

XML starts and ends in the git repository. I found that the attributes of the elements processed by XMLSerializer change in order, which leads to false changes in my repository, for example:

- <literal><token kind="w" id="en-us-esv-xeaugcbzgo">sent</token><token kind="s" id="en-us-esv-xeaugcbzgw"> </token></literal>
+ <literal><token id="en-us-esv-xeaugcbzgo" kind="w">sent</token><token id="en-us-esv-xeaugcbzgw" kind="s"> </token></literal>

This is not a mistake with any tools that I use. Of course, the order of the attributes of the xml element should not matter . But since git is SCM line-oriented, these false and minor changes will be distracted from the real significant changes that I want to track.

Question: Is there a way to keep the serializer from overriding my attributes? Alternatively, are there any tools to indicate / limit the order of attributes?

Edited above for clarity . I know that according to the XML specification, "the order of the attribute specifications in the start-tag or element tag does not matter": http://www.w3.org/TR/REC-xml/#sec-starttags . Suffice it to say that the ordering of attributes is significant to me. :)

+3
source share
2 answers

I chose the direction of @Tomalak and “fixed” the order server. Fortunately, the original order was alphabetical, and the order created by XMLSerializer was reverse alphabetical. My XML server tool, lxml, maintains the order of the attributes of the document, so changing the order is simple:

xmls = json.loads(self.data['xmls'])
out = []
for xml in xmls:
    # DOM adds an XHTML namespace... silly DOM.
    xml = xml.replace('xmlns="http://www.w3.org/1999/xhtml"', '')
    tree = ET.fromstring(xml)
    for el in tree.xpath('//*'):
        attrs = dict(el.attrib)
        keys = el.attrib.keys()  # el.attrib preserves attribute order
        keys.reverse()  # But the browser DOM has reversed that order.
        # Put them back in the order we want.
        el.attrib.clear()
        for k in keys:
            el.attrib[k] = attrs[k]
    out.append(ET.tostring(tree, encoding=unicode))

My linear differences are useful again!

0

, , , . , , .

Edit:

. ? , , , , . , ?

, , , .

+1

Source: https://habr.com/ru/post/1761202/


All Articles