python - 使用包含命名空间的 lxml 解析 xml

标签 python xml-parsing namespaces lxml

我需要在 lxml 中的特定标签之后获取一些信息。
xml 文档看起来像这样

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/
ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <display-name>Community Bank</display-name>
    <description>WebGoat for Cigital</description>

        <context-param>
                <param-name>PropertiesPath</param-name>
<param-value>/WEB-INF/properties.txt</param-value>
                <description>This is the path to the properties file from the servlet root</description>
        </context-param>

    <servlet>
        <servlet-name>Index</servlet-name>
<servlet-class>com.cigital.boi.servlet.index</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Index</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>Index</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>

我想阅读 com.cigital.boi.servlet.index 。

我已经使用此代码读取 servlet 下的所有内容
    context = etree.parse(handle)
    list = parser.xpath('//servlet')
    print list

列表不包含任何内容
更多信息:遍历上下文字段我找到了这些行。
<Element {http://java.sun.com/xml/ns/j2ee}servlet-name at 2ad19e6eca48>
<Element {http://java.sun.com/xml/ns/j2ee}servlet-class at 2ad19e6ecaf8>

我在想,因为我在搜索时没有包含 namespace ,所以输出是空列表。
请建议 hoe 在 servlet-class 标签中读取“com.cigital.boi.servlet.index”

最佳答案

尝试以下操作:

from lxml import etree
context = etree.parse(handle)
print next(x.text for x in context.xpath('.//*[local-name()="servlet-class"]'))

选择:
from lxml import etree
context = etree.parse(handle)
nsmap = context.getroot().nsmap.copy()
nsmap['xmlns'] = nsmap.pop(None)
print next(x.text for x in context.xpath('.//xmlns:servlet-class', namespaces=nsmap))

关于python - 使用包含命名空间的 lxml 解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18190393/

相关文章:

java - 捕获异常后的xml解析和验证

php - 使用php使用glob和数组将文件夹中的xml文件上传到Mysql

PHP命名空间从不同目录调用函数

silverlight - 实体命名空间未出现在 Silverlight 项目中

python - 如何更改seaborn散点图中的专色边缘颜色

python - 在 Python 中强制/转换为正确类型的最佳位置

xml - phobos 的 std.xml 的状态是什么

php - 使用 PHP 和 XPATH 呈现嵌入在 XML 节点中的 XML 节点

Python、NLTK 无法导入 "parse_cfg"?

Python:For 循环不会完成