Reputation: 39
i use this code to parse a xml data in java but give me a errors:
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());
this is the xml data:
<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>
its give me this errors in this part in the code :
Document dom = db.parse(is);
this is the error:
[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)
thanks for any help.
Upvotes: 0
Views: 522
Reputation: 60
Two workarounds: Just before the sentence: Document dom = db.parse(is); you should read entire inputstream in a string and remove the invalid line . Otherwise, if server don't resolve the bug, you can replace the first line with
Upvotes: 0
Reputation: 2538
You could replace first line of xml by adding xml = xml.replaceFirst("<xml version=\"1.0\" encoding=\"UTF-8\">", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
after xml = readUrl(conn);
.
Upvotes: 0
Reputation: 4176
The first line of your xml must be <?xml version="1.0" encoding="UTF-8"?>
, otherwise it is considered as a tag and hence the error.
Upvotes: 1
Reputation: 1155
The first line of your XML is incorrect. Change it to <?xml version="1.0" encoding="UTF-8"?>
Upvotes: 0