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
答案 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?它非常强大!