所以我的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) 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”
答案 0 :(得分:2)
您必须采用该元素的尾巴。
请从下面的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)