【问题标题】:Python: findall with xmlns prefixPython:带有 xmlns 前缀的 findall
【发布时间】:2015-01-25 11:10:26
【问题描述】:

我有多个 XML 文档要解析,它们都具有相同的元素名称,但每个文档都有自己独特的命名空间。

如何自行提取命名空间,以便将其作为“findall”循环的前缀包含在内?

例如,这是一个 XML 文件...

<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>

这是开始的示例代码...

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?

【问题讨论】:

  • 有多种 Python 模块用于解析 XML,因此请在问题中说明您使用的是哪个模块,这样人们就不必猜测了。
  • PM 2Rings,也许是 xml.etree.ElementTree 因为 Dan 使用命名空间 ET,我猜。但为了清楚起见,最好说得具体一点。
  • 正确,我使用的是 xml.etree.ElementTree

标签: python xml


【解决方案1】:

我不知道你到底想做什么,但我猜:

  • 您使用 xml.etree.ElementTree,
  • 并且您想从变量root 中提取xmlns 值。

root.tag 包含一个类似'{urn:ASC:CDL:v1.2}ColorCorrectionCollection' 的字符串,那么使用下面的代码怎么样?

root.tag[:root.tag.find('}') + 1]
# => '{urn:ASC:CDL:v1.2}'

【讨论】:

猜你喜欢
  • 2020-10-14
  • 1970-01-01
  • 2013-06-15
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2015-01-15
相关资源
最近更新 更多