xmlpath 解析xml
时间: 2023-03-01 20:11:30 浏览: 64
XPath is a language that can be used to select nodes from an XML document. It provides a way to navigate the elements and attributes of an XML document, allowing you to select the specific data you need.
Here is an example of how to use XPath to select nodes from an XML document:
```
from lxml import etree
# parse the XML document
xml = '''
<root>
<element attribute="value">
<sub_element>sub value</sub_element>
</element>
<element attribute="another value">
<sub_element>another sub value</sub_element>
</element>
</root>
'''
tree = etree.fromstring(xml)
# use XPath to select nodes
result = tree.xpath('//element/sub_element/text()')
print(result)
```
Output:
```
['sub value', 'another sub value']
```
In this example, the XPath expression `//element/sub_element/text()` is used to select the text content of all `sub_element` elements that are children of `element` elements, no matter where they are located in the document. The `text()` function is used to extract the text content of the selected nodes.