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<Element> list = root.getChildren();
if (list!=null)
{
for (int i = 0; i < list.size(); 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;
}
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 < len; 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);
return map;
}