【发布时间】:2014-06-15 12:40:47
【问题描述】:
我使用此代码在 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 的其余部分。
-
它的 Okey 我从服务器中删除它并正常工作,谢谢
标签: java xml parsing dom xml-parsing