Choosing a specific XML node using lxml in Python

时间:2015-10-29 15:59:10

标签: python xml python-2.7

I'm from a VBScript background and new to lxml with Python.

In VBScript, to choose a specific node, I would simply do something like:

Set myNode = xmlDoc.selectSingleNode("/node1/node2/myNode").

What I have done with Python:

from lxml import etree
xmlDoc = etree.parse(fileName)
myNode = 

Question: So what should be written in front of myNode to be able to select it?

Preferably without using XPath? Also taking lxml into account

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

myNode = xmlDoc.find('node2/myNode')

etree.parse函数将返回根节点(即您的node1),因此您不需要使用绝对路径。

示例

content = '''
<root>
<div>
  <p>content 1</p>
</div>
</root>
'''

from lxml import etree

xmlDoc = etree.fromstring(content)
paragraph_element = xmlDoc.find('div/p')
print(paragraph_element)

<强>输出

<Element p at 0x9f54bc8>

注意: 对于我的例子,我使用了函数etree.fromstring。这纯粹是出于演示目的,因此您可以使用字符串查看可行的示例。在处理文件而不是字符串时,函数etree.parse应该生成相同的结果。

旁白:为什么不使用XPath?它非常强大!