XML生成和解析

前端之家收集整理的这篇文章主要介绍了XML生成和解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、DOM方式解析XML

给予DOM的解析方式,是把整个XML文档加载到内存,转化成DOM树,可以随机的访问DOM树的任何数据,速度快、比较灵活,但是消耗资源比较多,不适用大的xml文档解析,测试超过10M内存溢出。

public class DOM01 {

    public static void printAttr(Node node){
        NamedNodeMap map = node.getAttributes();
        for(int i=0;i<map.getLength();i++){
            Node attrNode = map.item(0);
            System.out.println(attrNode.getNodeName()+":"+attrNode.getFirstChild().getNodeValue());
        }
    }
    
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("src/student.xml");
            NodeList nodeLlist =  doc.getElementsByTagName("students");
            Element element = (Element)nodeLlist.item(0);
            NodeList studentNodeList = element.getElementsByTagName("student");
            for(int i=0;i<studentNodeList.getLength();i++){
                Element e = (Element)studentNodeList.item(i);
                
                //e.getElementsByTagName("name").item(0).getFirstChild().setNodeValue("haha");
                System.out.println(e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
                printAttr(e.getElementsByTagName("name").item(0));
            }
//            System.out.println("姓名:"+element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2、SAX方式解析xml

SAX工作原理是对文档顺序扫描,当扫描到文档开始与结束、元素开始结束等地方时通知回调函数做出相应的动作,然后继续扫描,直至文档结束。消耗资源比较少,适合大文档解析,但是只能读取不能修改,开发也较复杂。

public class SAX extends DefaultHandler{
	
	private List<Student> students = null;
	private Student student = null;
	private String preTag = null;//记录上一个节点名称
	
	@Override
	public void startDocument() throws SAXException {
		System.out.println("开始读取学生信息");
		students  = new ArrayList<Student>();
	}

	@Override
	public void endDocument() throws SAXException {
		System.out.println("\n 信息读取完毕");
	}

	@Override
	public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
		if("student".equals(qName)){
			student = new Student();
			student.setId(attributes.getValue(0));
		}preTag = qName;
	}

	@Override
	public void endElement(String uri,String qName) throws SAXException {
		if("student".equals(qName)){
			 students.add(student);
			 student = null;
		}preTag = null;
	}

	@Override
	public void characters(char[] ch,int start,int length) throws SAXException {
		if(preTag != null){
			String content = new String(ch,start,length);
			if("name".equals(preTag)){
				student.setName(content);
			}else if("sex".equals(preTag)){
				student.setSex(content);
			}else if("age".equals(preTag)){
				student.setAge(content);
			}
		}
	}

	public static void main(String[] args) throws Exception{
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SAX sax = new SAX();
		parser.parse("src/student.xml",sax);
		for(Student student : sax.students){
			System.out.println(student);
		}
	}
	
}

JDOM和DOM4j解析xml:

两个都是解析XML优秀的框架,但是两者也有区别,具体可以参考http://www.cnblogs.com/zhi-hao/p/4016363.html

JDOM封装xml实例:

public class JDOM01 {

	public static void main(String[] args) throws Exception{
		Element student = new Element("student");
		
		Attribute id = new Attribute("id","001"); 
		Attribute aa = new Attribute("aa","xx"); 
		student.setAttribute(id);
		student.setAttribute(aa);
		
		Element name = new Element("name");
		Element age = new Element("age");
		Element sex = new Element("sex");
		
		name.setText("张三");
		student.addContent(name);
		sex.setText("男");
		student.addContent(sex);
		age.setText("18");
		student.addContent(age);
		
		Document document = new Document(student);
		XMLOutputter outputter = new XMLOutputter();
		outputter.setFormat(outputter.getFormat().setEncoding("UTF-8"));
		
		outputter.output(document,new FileOutputStream("src/student2.xml"));
	}
}

JDOM解析xml实例:

public class JDOM02 {

	public static void main(String[] args) throws Exception{
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build("src/student.xml");
		Element students = document.getRootElement();
		List studentList = students.getChildren("student");
		for(int i=0;i<studentList.size();i++){
			Element student = (Element)studentList.get(i);
			String id = student.getAttributeValue("id");
			String name = student.getChildText("name");
			String sex = student.getChildText("sex");
			String age = student.getChildText("age");
			System.out.println("学号:"+id+",姓名:"+name+",性别:"+sex+",年龄:"+age);
		}
		
	}
}

DOM4j封装xml实例:

public class DOM4j01 {

	public static void main(String[] args) throws Exception{
		Document document = DocumentHelper.createDocument();
		Element studentElement = document.addElement("student");
		studentElement.addAttribute("id","001");
		studentElement.addAttribute("aa","xx");
		Element name = studentElement.addElement("name");
		name.setText("张三");
		Element sex = studentElement.addElement("sex");
		sex.setText("男");
		Element age = studentElement.addElement("age");
		age.setText("20");
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		XMLWriter writer = new XMLWriter(new FileOutputStream("src/student3.xml"),format);
		writer.write(document);
		writer.close();
	}
}

DOM4j解析xml实例:

public class DOM4j02 {

	public static void main(String[] args) throws Exception{
		SAXReader saxReader = new SAXReader();
		Document doc =  saxReader.read("src/student.xml");
		
		Element rootElement = doc.getRootElement();
		@SuppressWarnings("rawtypes")
		Iterator iter = rootElement.elementIterator();
		while(iter.hasNext()){
			Element studentElement = (Element)iter.next();
			System.out.println("学号:"+studentElement.attributeValue("id"));
			System.out.println("姓名:"+studentElement.elementText("name"));
			System.out.println("=========================================");
		}
	}
}

总的来说DOM4J是最好的,目前许多开源项目中也大量采用 DOM4J,例如大名鼎鼎的 Hibernate 也用 DOM4J 来读取 XML 配置文件。如果不考虑可移植性,那就采用DOM4J吧

原文链接:https://www.f2er.com/xml/294727.html

猜你在找的XML相关文章