簡體   English   中英

如何在Java中使用DOM解析xml

[英]how to parse xml using DOM in java

我使用此代碼來解析Java中的xml數據,但給我一個錯誤:

    Informations info=new Informations();
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/XML");
    String xml="";
    xml = readUrl(conn);     
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        Document dom = db.parse(is);
        Element root = dom.getDocumentElement();
        NodeList items = root.getElementsByTagName("deal");


        //----titre
        NodeList titre = dom.getElementsByTagName("titre");
        Element line = (Element) titre.item(0);
        info.setTitre(getCharacterDataFromElement(line));
        System.out.println("Titre: " + info.getTitre());
       //----reduction
        NodeList reduction = dom.getElementsByTagName("reduction");
        line = (Element) reduction.item(0);
        info.setReduction(getCharacterDataFromElement(line));
        System.out.println("Reduction: " + info.getReduction());

這是xml數據:

<xml version="1.0" encoding="UTF-8">
<deals>
 <deal>
  <type>Occasion</type>
  <datedebutdeal>0000-00-00 00:00:00</datedebutdeal>
  <datefindeal>2014-04-30 00:00:00</datefindeal>  
  <reduction>25.93</reduction>
  <titre>A4</titre>
 </deal>
</deals>

它在代碼的這一部分給我這個錯誤:

  Document dom = db.parse(is);

這是錯誤:

[Fatal Error] :2069:1: XML document structures must start and end within the same   entity.
org.xml.sax.SAXParseException: XML document structures must start and end within the same entity.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)

謝謝你的幫助。

xml的第一行必須為<?xml version="1.0" encoding="UTF-8"?> ,否則它將被視為標簽,因此會出現錯誤。

XML的第一行不正確。 將其更改為<?xml version="1.0" encoding="UTF-8"?>

您可以通過添加xml = xml.replaceFirst("<xml version=\\"1.0\\" encoding=\\"UTF-8\\">", "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>"); xml = readUrl(conn);

兩種解決方法:在句子之前:Document dom = db.parse(is); 您應該以字符串形式讀取整個inputstream並刪除無效行。 否則,如果服務器無法解決該錯誤,則可以將第一行替換為

暫無
暫無

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

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