xml 是一种可可扩展标记语言,用于标记电子文件使其具有结构性的标记语言。标记指计算机能理解得信息符号,通过此种标记,计算机之间可以处理包含各种的信息。也可以用来标记数据,定义数据类型,是一种允用户对自己的标记语言进行定义的源语言。 dom4j是一个java的xml api,用来读写xml文件的。
相应的代码:
import java.io.FileInputStream;import java.io.IOException;import java.util.Iterator;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * Description: * 使用domj4解析xml文件 * * @author Lee * */public class Parser { /** * Description : * 使用dom4j的SAXReader类解析xml文件 * * */ public static void test1(){ /* * SAXReader creates a DOM4J tree from SAX parsing events. * */ SAXReader sax = new SAXReader(); try{ /* * Reads a document from a given stream. * return a newly document instance. * */ Document doc = sax.read( new FileInputStream( "C://Users//lenovopc//workspace//" + "Demo//src//PRop.xml")); //获取根元素 Element rootElement = doc.getRootElement(); //获取根元素的迭代器 Iterator iterator = rootElement.elementIterator(); while(iterator.hasNext()){ //获取子元素 Element subElement = (Element)iterator.next(); /* * This returns the attribute value for the attribute with the given name * and any namespace or null if there is no such attribute * or the empty string if the attribute value is empty. * */ //获取子元素的id属性的值 String id = subElement.attributeValue("id"); //或许子元素的孙元素的值 String name = subElement.elementText("name"); String sex = subElement.elementText("sex"); System.out.println("id="+id+",name="+name+",sex="+sex); } }catch(IOException e){ e.printStackTrace(); }catch(DocumentException e){ e.printStackTrace(); } } public static void main(String[] args) { test1(); }}新闻热点
疑难解答