0

I have multiple XML documents to parse, all with the same Element names but each document has it's own unique namespace.

How do I extract the namespace on its own, so I can include it as a prefix for my "findall" loops?

For example, here's one of XML files...

<ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2">
    <ColorCorrection id="af/af-123/neutral">
          <SOPNode>
               <Slope>2 1 1</Slope>
               <Offset>0 0 0</Offset>
               <Power>1 1 1</Power>
          </SOPNode>
          <SATNode>
               <Saturation>1</Saturation>
          </SATNode>
    </ColorCorrection>
    <ColorCorrection id="af/af-123/beauty">
          <SOPNode>
               <Slope>1.5 1.2 0.9</Slope>
               <Offset>0 0 0</Offset>
               <Power>1 1 1</Power>
          </SOPNode>
          <SATNode>
               <Saturation>0.8</Saturation>
          </SATNode>
    </ColorCorrection>

Here's example code to start...

import xml.etree.ElementTree as ET
tree = ET.parse(file)
root = tree.getroot()
for elem in root.findall("ColorCorrection"):
    # the above won't find anything,
    # as I need specify "{urn:ASC:CDL:v1.2}" as prefix.
    # how can I GET "{urn:ASC:CDL:v1.2}" into a variable?
Dan
  • 511
  • 2
  • 9
  • 19
  • There are various Python modules in use for parsing XML, so please mention which one you're using in your question so people don't have to guess. – PM 2Ring Jan 25 '15 at 11:28
  • PM 2Rings, maybe it's xml.etree.ElementTree because Dan uses namespace ET, I guess. But for clarity, it's better to be told concretely. – gh640 Jan 25 '15 at 11:36
  • Correct, I'm using xml.etree.ElementTree – Dan Jan 25 '15 at 14:54

1 Answers1

1

I don't know what you actually want to do, but I guess:

  • you use xml.etree.ElementTree,
  • and you want to extract xmlns value from the variable root.

root.tag includes a string like '{urn:ASC:CDL:v1.2}ColorCorrectionCollection' and how about using the following code?

root.tag[:root.tag.find('}') + 1]
# => '{urn:ASC:CDL:v1.2}'
gh640
  • 164
  • 2
  • 6
  • FYI. http://stackoverflow.com/questions/1953761/accessing-xmlns-attribute-with-python-elementree – gh640 Jan 25 '15 at 11:55