我在解析 XML 文件时遇到的一个案例

One Case I came through while parsing my XML file

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

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

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

(假设我从变量 'tree' 中的文件中读取了这个 XML) Python3.5代码:

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

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

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

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

你必须拿那个元素的尾巴。

请检查下方 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)