David542 David542 - 3 months ago 12
Python Question

Quick way to Upper every value in xml?

I have the following xml:

<Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info>
<Type>TVSeries</Type>
</Item>


What would be the quickest way to
UPPER
all the values? For example:

<Item>
<Platform>ITUNES</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>COMMANDER IN CHIEF</Name>
<Studio>ABC</Studio>
</Info>
<Type>TVSERIES</Type>
</Item>

Answer

You can find all elements and call upper() on each element's text:

import lxml.etree as ET

data = """<Item>
  <Platform>itunes</Platform>
  <PlatformID>102224185</PlatformID>
  <Info>
    <LanguageOfMetadata>EN</LanguageOfMetadata>
    <Name>Commander In Chief</Name>
    <Studio>abc</Studio>
  </Info>
  <Type>TVSeries</Type>
</Item>
"""

root = ET.fromstring(data)
for elm in root.xpath("//*"):  # //* would find all elements recursively
    elm.text = elm.text.upper()

print(ET.tostring(root))

Prints:

<Item>
  <Platform>ITUNES</Platform>
  <PlatformID>102224185</PlatformID>
  <Info>
    <LanguageOfMetadata>EN</LanguageOfMetadata>
    <Name>COMMANDER IN CHIEF</Name>
    <Studio>ABC</Studio>
  </Info>
  <Type>TVSERIES</Type>
</Item>

This though does not cover cases when you, for example, have a tail of an element - e.g. have <Studio>ABC</Studio>test instead of just <Studio>ABC</Studio>. To support that as well, put the following under the for loop as well:

elm.tail = elm.tail.upper() if elm.tail else None