0

Consider I have a string that looks like the following below. It's type is string but it will always represents an xml document. I'm researching available python libraries for xml. How can I update a value in between 2 specific tags? What library would I be using for that?

<?xml version="1.0"?>
<PostTelemetryRequest xmlns:ns2="urn:com:onstar:global:common:schema:PostTelemetryData:1">
  <ns2:PartnerVehicles>
    <ns2:PartnerVehicle>
      <ns2:partnerNotificationID>251029655</ns2:partnerNotificationID>
    </ns2:PartnerVehicle>
  </ns2:PartnerVehicles>
</PostTelemetryRequest>

For instance, if the input is the string above how can I update the value between <ns2:partnerNotificationID> and </ns2:partnerNotificationID> tags to a new value?

0

1 Answer 1

1

This is the base code:

>>> from xml.etree import ElementTree
>>> s = """<?xml version="1.0"?>
<PostTelemetryRequest xmlns:ns2="urn:com:onstar:global:common:schema:PostTelemetryData:1">
  <ns2:PartnerVehicles>
    <ns2:PartnerVehicle>
      <ns2:partnerNotificationID>251029655</ns2:partnerNotificationID>
    </ns2:PartnerVehicle>
  </ns2:PartnerVehicles>
</PostTelemetryRequest>
"""
>>> root = ElementTree.fromstring(s)
>>> for e in root.iter():
...  if e.tag=='{urn:com:onstar:global:common:schema:PostTelemetryData:1}partnerNotificationID':
...   e.text='mytext'
... 
>>> etree.ElementTree.tostring(root)
b'<PostTelemetryRequest xmlns:ns0="urn:com:onstar:global:common:schema:PostTelemetryData:1">\n  <ns0:PartnerVehicles>\n    <ns0:PartnerVehicle>\n      <ns0:partnerNotificationID>mytext</ns0:partnerNotificationID>\n    </ns0:PartnerVehicle>\n  </ns0:PartnerVehicles>\n</PostTelemetryRequest>'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.