简体   繁体   中英

Can't parse web.xml file in Java

I'm trying to parse a web.xml file in Java using org.apache.tomcat.util.descriptor.web.WebXmlParser but I don't get it.

The program is really simple:

public WebXml read() {
    WebXml webXml = new WebXml();

    WebXmlParser parser = new WebXmlParser(false, true, true);

    try (InputStream is = Reader.class.getResourceAsStream("/web.xml")) {
        boolean success = parser.parseWebXml(new InputSource(is), webXml, false);
        if (!success) {
            throw new IllegalStateException("Error parsing");
        }
    } catch (IOException e) {
        throw new IllegalStateException("Error reading", e);
    }

    return webXml;
}

The web.xml is in the project's root and it has a servlet defined:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>demoServlet</servlet-name>
        <servlet-class>com.demo.DemoServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>demoServlet</servlet-name>
        <url-pattern>/demo</url-pattern>
    </servlet-mapping>

</web-app>

When I try to parse the web.xml with the above snippet I get the following error:

SEVERE: Parse Error at line 4 column 24: cvc-elt.1: Cannot find the declaration of element 'web-app'.
org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 24; cvc-elt.1: Cannot find the declaration of element 'web-app'.

I don't understand the error because IMHO the web.xml is correctly written.

I've prepared a sample project to show the error: https://github.com/itelleria/webxml-parser

I would appreciate any help with this error.

Thanks in advance.

对我来说,它可以禁用验证

WebXmlParser parser = new WebXmlParser(false, false, true);

If you want to count the number of servlet or any tags you can use this :

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    Document doc = null;
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    doc = docBuilder.parse("D:\\ECLIPSE-WORKSPACE\\demo-xml-parser\\src\\main\\resources\\web.xml");  // path of your testNgXml
    NodeList parameterNodes = doc.getElementsByTagName("servlet");
    System.out.println(parameterNodes.getLength());
}

I have your project and trying to debug the problem, in the mean time you can use above mentioned method. Please do not mind if it is not what you are looking for.
It is just a suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM