簡體   English   中英

Java-如何將字符串轉換為xml文檔

[英]Java - How to convert string to xml whitout doc

我需要在服務器中發出獲取請求以獲取信息。 我要求將此信息保存在xml中,這里的問題是我試圖將此答案保留為xml對象。 我找到了很多答案,但只能創建文檔,而不僅僅是創建對象(我不得不說不允許我在客戶端創建文件)。

我現在有以下代碼:

    URL url;
    String urlForScores = urlToRead+"format=xml";  
    HttpURLConnection conn = null;
    String line;
    String result = "";
    try {
       url = new URL(urlForScores);
       conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("GET");
       conn.setRequestProperty("Accept", "application/xml");

       readerChannel = new BufferedReader(
                              new InputStreamReader(conn.getInputStream()));
       while ((line = readerChannel.readLine()) != null) {
          result += line;
       }
       readerChannel.close();



       JAXBContext jc = JAXBContext.newInstance(String.class);
       Unmarshaller unmarshaller = jc.createUnmarshaller();
       StreamSource xmlSource = new StreamSource(new StringReader(result));
       JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
       System.out.println(je.getValue());

    } catch (Exception e) {
       e.printStackTrace();
    }

你能幫我嗎 ??

謝謝 !

要使用JAXB編組器,您應該使用JAXB批注。 我確定java.lang.String不會帶有任何注釋。 您實際上必須基於XML結構對類建模,並使用JAXB批注對其進行批注,然后可以使用JAXB編組器來解組字符串。

在您的示例中使用JAXB要求您構建一個Object結構,該結構與接收到的XML文件中的數據完全相同。 如果您沒有用於自動構建JAXB類的XML模式,這可能會變得很復雜。

因此,構建文檔要簡單得多,並且您無需為此解決方案將任何內容保存到文件中:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document dc = parser.parse(conn.getInputStream());

暫無
暫無

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

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