JAVA 解析字符串格式的xml(非xml文档)错误
本帖最后由 guoyao_Work 于 2012-12-20 15:22:33 编辑 上代码:
//创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder(false);
try
{
//通过输入源构造一个Document
Document doc = sb.build(new InputSource(new StringReader(XmlDoc)));
//取的根元素
Element root = doc.getRootElement();
System.out.println(root.getName());//输出根元素的名称(测试)
//得到根元素所有子元素的集合
List list = root.getChildren();
if (list!=null)
{
for (int i = 0; i
{
Element elchild=(Element)list.get(i);
System.out.println("节点="+elchild.getName()+"///Text="+elchild.getValue());
}
}
return true;
}
catch (JDOMException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
执行到:Document doc = sb.build(new InputSource(new StringReader(XmlDoc)));就报错了
错误信息如下:
org.jdom.input.JDOMParseException
org.jdom.input.JDOMParseException: Error on line 1: : XML-20100: (Fatal Error) Expected 'EOF'.
------解决方案--------------------
这里以前写过一个。主要是你的string是否是xml标准格式的,如果不是的需要拼接成xml格式
public static Map setParseXML(String xml) throws Exception{
Map map = new HashMap();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document doc = builder.parse(is);
Element root = doc.getDocumentElement();
List colName = new ArrayList();
String name = "";
List colValue = new ArrayList();
String value = "";
NodeList children = root.getChildNodes();
int len = children.getLength();
for (int i = 0; i
Node node = children.item(i);
if (node instanceof Element) {
if (node instanceof Element) {
Node text = node.getFirstChild();
if (text instanceof Text) {
value = text.getNodeValue();
}else{
value = "";
}
name = node.getNodeName();
colName.add(name);
colValue.add(value);
}
}
}
map.put("colName", colName);
map.put("colValue", colValue);