java xml字符非法_JAVA 解析字符串格式的xml(非xml文档)异常

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值