1

My xml file:

<?xml version='1.0' encoding='UTF-8'?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <CstmrCdtTrfInitn>
        <CtgyPurp>.   // ---->i want to change this tag
          <Cd>SALA</Cd> //-----> no change
        </CtgyPurp>   // ----> i want to change this tag
  </CstmrCdtTrfInitn>
</Document>

I want to make a change in the xml file:

<CtgyPurp></CtgyPurp> change in <newName></newName>

I know how to change the value within a tag but not how to change/modify the tag itself with lxml

saro
  • 705
  • 3
  • 13
  • Your question isn't clear: do you want to change the name of the `` element to `` but leave the `SALA` element as-is? Also, your sample xml is not well formed; can you edit the question and fix it? – Jack Fleeting Nov 03 '22 at 13:15
  • yes your are right i only want to change in . I changed the xml. – saro Nov 03 '22 at 13:21
  • Unfortunately, your xml is still not well formed; try to run it through a validator like https://www.freeformatter.com/xml-validator-xsd.html – Jack Fleeting Nov 03 '22 at 13:25
  • Maybe this helps: https://stackoverflow.com/a/36459411 – tobifasc Nov 03 '22 at 13:27
  • i changed the xml, made it shorter. This should work – saro Nov 03 '22 at 13:43
  • tx Jack Fleeting, this is working. iam struggling with the xmls. Not sure when to use which package (elementtree, xpath, etree). – saro Nov 03 '22 at 19:03
  • @saro - There's a lot to learn, but it's actually pretty interesting stuff, believe it or not. Good luck! – Jack Fleeting Nov 03 '22 at 20:15

1 Answers1

0

Something like this should work - note the treatment of namespaces:

from lxml import etree
ctg = """[your xml above"]"""

doc = etree.XML(ctg.encode())
ns = {"xx": "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"}
target = doc.xpath('//xx:CtgyPurp',namespaces=ns)[0]
target.tag = "newName"
print(etree.tostring(doc).decode())

Output:

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <CstmrCdtTrfInitn>
        <newName>.   // ----&gt;i want to change this tag
          <Cd>SALA</Cd> //-----&gt; no change
        </newName>   // ----&gt; i want to change this tag
  </CstmrCdtTrfInitn>
</Document>
Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45