首页 > 代码库 > 解析XML
解析XML
一、dom4j
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element;
Document document = DocumentHelper.parseText(xmltojopo); //document Element root = document.getRootElement(); for(Iterator i = root.elementIterator(); i.hasNext(); ){//遍历Info Element infos = (Element) i.next();
if(infos.getName().equals("caseInfo")){ for(Iterator j = infos.elementIterator(); j.hasNext();){//遍历元素 Element elememtOfInfo = (Element) j.next(); //得到属性 String elementOfInfoName = elememtOfInfo.getName();//得到属性的类型 String elementOfInfoValue = http://www.mamicode.com/elememtOfInfo.getText();//得到属性的值
caseInfoMap.put(elementOfInfoName, elementOfInfoValue); } }
二、jdom
import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.input.sax.XMLReaderSAX2Factory;
参数为File类型的xml
InputStream xmlFileStream = null; xmlFileStream = new FileInputStream(xmlFile); SAXBuilder builder=new SAXBuilder(new XMLReaderSAX2Factory(false, null)); Document document = builder.build(xmlFileStream);//获得文档对象 Element root = document.getRootElement();//获得根节点 Element consignElement = root.getChild("caseInfo"); List<Element> elements = caseInfoElement.getChildren(); for(Element ele : elements){ System.out.println(ele.getName()); System.out.println(ele.getTextTrim()); Field field = objectClz.getDeclaredField(chiledEle.getName()); field.setAccessible(true); System.out.println(field.getType().getName()); }
参数为String类型的xml 做String到InputStream的转换
InputStream xmlStream = null;
xmlStream = new ByteArrayInputStream(dataInfo.getBytes("utf-8"));
SAXBuilder builder=new SAXBuilder(new XMLReaderSAX2Factory(false, null)); Document document = builder.build(xmlStream);//获得文档对象
Element root = document.getRootElement();//获得根节点
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。