【问题标题】:Why ElementTree can't parse this XML tag correctly?为什么 ElementTree 不能正确解析这个 XML 标签?
【发布时间】:2013-09-23 07:15:42
【问题描述】:

XML 文件如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<MINiML
   xmlns="http://www.ncbi.nlm.nih.gov/geo/info/MINiML"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.ncbi.nlm.nih.gov/geo/info/MINiML http://www.ncbi.nlm.nih.gov/geo/info/MINiML.xsd"
   version="0.5.0" >

  <Contributor iid="contrib1">
    <Person><First>ENCODE</First><Last>DCC</Last></Person>
    <Email>encode-help@lists.stanford.edu</Email>
    <Organization>ENCODE DCC</Organization>
    <Address>
      <Line>300 Pasteur Dr</Line>
      <City>Stanford</City>
      <State>CA</State>
      <Zip-Code>94305-5120</Zip-Code>
      <Country>USA</Country>
    </Address>
  </Contributor>
</MINiML>

这是我在 Python 中使用 ElementTree 的方法:

import xml.etree.cElementTree as ET
tree=ET.parse("the_file_above.xml")
root = tree.getroot()
for c in root:
    print c.tag, c.attrib

返回:

{http://www.ncbi.nlm.nih.gov/geo/info/MINiML}Contributor {'iid': 'contrib1'}

c.tag 的值是'{http://www.ncbi.nlm.nih.gov/geo/info/MINiML}Contributor',我预计是Contributor。我不确定标签中的长网址是如何混合的。有人对此有想法吗?

【问题讨论】:

  • 这是这个标签来自的 XML 命名空间。我确信库也有办法获取本地标签名称。

标签: python html xml tags elementtree


【解决方案1】:

这个库(和其他库一样)尝试将使用的命名空间编码到标签名称中。这是通过在花括号中添加命名空间来完成的。所以这只是一个你可能不知道的功能,对你来说可能很麻烦。但是,如果您将来自各种来源的 XML 与各种名称空间混合在一起,否则标签名称会发生​​冲突。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多