SaxParseException 元素类型"hr"必须由匹配的结束标记"</hr>"终止。使用 JAXB 读取 XML 时



我正试图从jaxb给出的链接中读取以下xml。我一直得到以下异常。文档中没有hr标签

下面是我的代码:
final JAXBContextjaxbContext=JAXBContext.newInstance(EuropeanParliamentMemberResponse.class);
final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
final JAXBElement<EuropeanParliamentMemberResponse> response = jaxbUnmarshaller.unmarshal(new StreamSource(url), EuropeanParliamentMemberResponse.class);

这里有一个例外:

org.xml.sax.SAXParseException; systemId: http://www.europarl.europa.eu/meps/en/full-list/xml; lineNumber: 6; columnNumber: 3; The element type "hr" must be terminated by the matching end-tag "</hr>".]

我做错了什么?

你得到这个错误的原因是因为你在URL中使用了错误的协议。用https代替http

当您使用http时,服务器生成一个"301 -永久移动";回应:

<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center>
<h1>301 Moved Permanently</h1>
</center>
<hr>
<center>nginx</center>
</body>
</html>

您可以看到<hr>标记导致错误(它对预期的XML内容类型无效)。

如果您使用httpURL,您的浏览器将正确地处理这个—但是您的JAXB解组器不会。

假设您的类上有所有正确的JAXB注释,那么问题中的代码应该可以使用更新后的URL工作(它对我有效):

https://www.europarl.europa.eu/meps/en/full-list/xml

解决这类问题的几个建议:

  1. 在浏览器中转到主页:http://www.europarl.europa.eu-您将看到您被重定向到httpsURL。

  2. 您可以使用Java的HttpClient(从Java 11起可用)提取我上面展示的重定向响应:

String url = "http://www.europarl.europa.eu/meps/en/full-list/xml";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();

打印响应体,您可以在其中看到重定向消息。

最新更新