【问题标题】:One Case I came through while parsing my XML file我在解析 XML 文件时遇到的一个案例
【发布时间】:2018-10-31 06:07:52
【问题描述】:

所以我的 XML 文件有点像这样:

<Root>
  <S_CellBody Id = "16393">
   <?OldID 16393?>
   <ph Id = "19393">SELx</ph>
    (x=0)
  </S_CellBody>
</Root>

我想在 python 中使用 ElementTree 库从这个 XML 中提取 (x=0) 我正在尝试使用以下代码访问它:

(假设我从变量“树”中的文件中读取此 XML) Python 3.5 代码:

root= tree.getroot()
s_cellbody= root.find('.//S_CellBody').text
print(s_cellbody)

但是上面的代码给了我输出'None'

我不明白发生了什么,因为“(x=0)”是标签“S_CellBody”下的文本。谁能解释一下!!!

EDIT1:S_cellBody 只是一个错字!抱歉,我已将其更正为“S_CellBody”

【问题讨论】:

标签: python xml elementtree


【解决方案1】:

你必须抓住那个元素的尾巴。

请从下面的 ipython 控制台检查代码,

In [1]: import xml.etree.ElementTree as ET

In [2]: cat myxml.xml
<Root>
  <S_CellBody Id = "16393">
   <?OldID 16393?>
   <ph Id = "19393">SELx</ph>
    (x=0)
  </S_CellBody>
</Root>

In [3]: tree = ET.parse('myxml.xml')

In [4]: root = tree.getroot()

In [5]: elem = root.find('S_CellBody')

In [6]: if elem:
   ...:     print(elem[0].tail)
   ...:     
/usr/local/bin/ipython:1: FutureWarning: The behavior of this method will change in future versions.  Use specific 'len(elem)' or 'elem is not None' test instead.
  #!/usr/bin/python

    (x=0)


In [7]: if elem is not None:
   ...:     print(elem[0].tail)
   ...:     

    (x=0)

【讨论】:

  • 不要写“那个元素的尾部”,最好写成“&lt;ph&gt;元素的尾部”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多