我在分析XML文件时遇到了一个案例

2024-06-07 16:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的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)

但上面的代码给我的输出是“无”

我不明白发生了什么,因为z'(x=0)'是标签'u CellBody'下的文本。有人能解释一下吗

EDIT1:S\u cellBody只是个打字错误!抱歉,我已将其更正为“S\u CellBody”


Tags: 文件代码idtreerootxmlfindph
1条回答
网友
1楼 · 发布于 2024-06-07 16:07:36

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

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

相关问题 更多 >

    热门问题