[英]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.