lxml:如何在不向每个搜索词添加xmlns(localhost)路径的情况下搜索字段?

时间:2016-05-21 12:45:23

标签: python python-2.7 lxml

我正在尝试使用lxml(3.6.0)

在SOAP xml文件中查找字段
...
<soap:Body>
<Request xmlns="http://localhost/">
<Test>
<field1>hello</field1>
<field2>world</field2>
</Test>
</Request>
</soap:Body>
...

在此示例中,我尝试查找field1field2

我需要添加搜索字词的路径,以找到字段:

print (myroot.find(".//{http://localhost/}field1").tag) # prints 'field1'
没有它,我找不到任何东西

print (myroot.find("field1").tag) # finds 'None'

有没有其他方法可以在不提供路径信息的情况下搜索字段标记(此处为field1)?

以下完整示例:

from lxml import etree

example = """<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body><Request xmlns="http://localhost/">
<Test><field1>hello</field1><field2>world</field2></Test>
</Request></soap:Body></soap:Envelope>
"""
myroot = etree.fromstring(example)

# this works
print (myroot.find(".//{http://localhost/}field1").text)
print (myroot.find(".//{http://localhost/}field2").text)

# this fails
print (myroot.find(".//field1").text)
print (myroot.find("field1").text)

评论:给出了SOAP请求的输入,我无法在实际中更改任何内容以使事情变得更容易。

1 个答案:

答案 0 :(得分:1)

有一种方法可以在使用XPath选择元素时忽略命名空间,但这不是一个好习惯。命名空间是有原因的。无论如何,有一种更简洁的方法来引用命名空间中的元素,即使用映射到命名空间uri的命名空间前缀,而不是每次都使用实际的命名空间uri:

<h2 class="chart-row__song">(.*?)</h2>