dom4j解析xml

来源:互联网 发布:放牛班的春天音乐知乎 编辑:程序博客网 时间:2024/06/07 18:39
import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class XmlUtil {public String getNodeValue(String xml, String nodeName)   {  String nodeValue = "";Document document = null;try{document = DocumentHelper.parseText(xml);List<Element> list = document.selectNodes("//*/"+nodeName);Iterator it = list.iterator();if(it.hasNext()){Element element = (Element) it.next();nodeValue =  element.getText();}}catch(Exception e){e.printStackTrace();}return nodeValue;}    public static void main(String[] args) {String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><note><to>George</to><from>John</from><heading>Reminder</heading><body>Don't forget the meeting!</body></note>";System.out.println(xml);String to = new XmlUtil().getNodeValue(xml, "to");String from = new XmlUtil().getNodeValue(xml, "from");String heading = new XmlUtil().getNodeValue(xml, "heading");String body = new XmlUtil().getNodeValue(xml, "body");System.out.println("to  >>  "+to);System.out.println("from  >>  "+from);System.out.println("heading  >>  "+heading);System.out.println("body  >>  "+body);}}


原创粉丝点击