1

I need to get some info after a specific tag in lxml. the xml doc looks like this

<?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>

I want to read com.cigital.boi.servlet.index .

I have used this code to read everything under servlets

    context = etree.parse(handle)
    list = parser.xpath('//servlet')
    print list

list contains nothing more info : iterating over the context field i found these lines.

<Element {http://java.sun.com/xml/ns/j2ee}servlet-name at 2ad19e6eca48>
<Element {http://java.sun.com/xml/ns/j2ee}servlet-class at 2ad19e6ecaf8>

I am thinking as I have not included name space while searching , output is empty list. please suggest hoe to read "com.cigital.boi.servlet.index" in the servlet-class tag

4

1 回答 1

7

尝试以下操作:

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))
于 2013-08-12T15:05:10.957 回答