Reputation: 619
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.
Upvotes: 0
Views: 1280
Reputation: 141
For me it worked with disabled validation
WebXmlParser parser = new WebXmlParser(false, false, true);
Upvotes: 2
Reputation: 1275
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.
Upvotes: 0