W3C还提供了一个实验性API来帮助自动验证。他们友好地要求您限制请求,并提供有关在本地服务器上设置验证器的说明。这肯定需要更多的工作,但如果您正在生成大量HTML页面,自动验证也是非常有意义的。
官方API位于
自2007年以来,允许通过Markup Validator Web Service API调用本地或远程W3C检查器。
有一个使用Jersey和moxy-Jaxb的单个Java类解决方案来读取SOAP响应。
这是使用它的Maven依赖项:
<dependency>
<groupId>com.bitplan</groupId>
<artifactId>w3cValidator</artifactId>
<version>0.0.2</version>
</dependency>
这是一个用于尝试的JUnit测试:
/**
* The URL of the official W3C markup validation service.
* If you'd like to run the tests against your own installation you might want to modify this.
*/
public static final String url = "http://validator.w3.org/check";
/**
* Test the w3cValidator interface with some HTML code
* @throws Exception
*/
@Test
public void testW3CValidator() throws Exception {
String preamble =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n" +
" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
"<html>\n" +
" <head>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
" <title>test</title>\n" +
" </head>\n" +
" <body>\n";
String footer = " </body>\n" +
"</html>\n";
String[] htmls = {
preamble +
" <div>\n" +
footer,
"<!DOCTYPE html><html><head><title>test W3CChecker</title></head><body><div></body></html>"
};
int[] expectedErrs = {1, 2};
int[] expectedWarnings = {1, 2};
int index = 0;
System.out.println("Testing " + htmls.length + " html messages via " + url);
for (String html : htmls) {
W3CValidator checkResult = W3CValidator.check(url, html);
List<ValidationError> errlist = checkResult.body.response.errors.errorlist;
List<ValidationWarning> warnlist = checkResult.body.response.warnings.warninglist;
Object first = errlist.get(0);
assertTrue("if first is a string, than moxy is not activated",
first instanceof ValidationError);
//System.out.println(first.getClass().getName());
//System.out.println(first);
System.out.println("Validation result for test " + (index+1) + ":");
for (ValidationError err:errlist) {
System.out.println("\t" + err.toString());
}
for (ValidationWarning warn:warnlist) {
System.out.println("\t" + warn.toString());
}
System.out.println();
assertTrue(errlist.size() >= expectedErrs[index]);
assertTrue(warnlist.size() >= expectedWarnings[index]);
index++;
}
} // testW3CValidator
展示如何在Ubuntu Linux系统上运行您自己的W3C验证器。