Mario
Mario

Reputation: 103

Output XML with single quotes instead of double for attribute values

I have this XML document, and I need to replace the dobule quotation marks with single quotes (the apostrophe):

<det nItem="1">
<prod>
    <cProd>0320</cProd>
<prod>  
</det>
<det nItem="2">
<prod>
    <cProd>0320</cProd>
<prod>  
</det>

I want it to be.

<det nItem='1'>
<prod>
    <cProd>0320</cProd>
<prod>  
</det>
<det nItem='2'>
<prod>
    <cProd>0320</cProd>
<prod>  
</det>

I have tried using ElementTree but it can't be configured to use a different quoting style.

Upvotes: 1

Views: 2829

Answers (1)

James
James

Reputation: 36608

You could parse the lines in the file to a new file, replacing the characters as you go. This swaps single quotes for &apos;, and then double quotes for single.

with open('file1.xml') as fp_in:
    with open('file2.xml') as fp_out:
        for line in fp_in:
            fp_out.write(line.replace("'", '&apos;').replace('"', "'"))

Upvotes: 3

Related Questions