簡體   English   中英

SaxParseException 元素類型“hr”必須由匹配的結束標記“終止</hr> “。在使用 jaxb 讀取 xml 時

[英]SaxParseException The element type "hr" must be terminated by the matching end-tag "</hr>". while reading xml with jaxb

我正在嘗試從帶有 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 的預期內容類型無效)。

如果您使用http URL,您的瀏覽器將正確處理此問題 - 但您的 JAXB 解組器不會。

假設您的課程中有所有正確的 JAXB 注釋,您問題中的代碼應該可以使用更新的 URL(它適用於我):

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

解決此類問題的一些建議:

  1. 在瀏覽器中轉到主頁: http://www.europarl.europa.eu ://www.europarl.europa.eu - 您將看到您被重定向到https URL。

  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();

這將打印響應正文,您可以在其中看到重定向消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM