[j2ee]java中的xml操作

一、XML简单介绍

     xml是可扩展标记语言,主要用来标记数据、定义数据类型,很适合万维网传输。

      xml特点:

  1.    xml是一种标记语言。非常类似HTML
  2.    xml的设计宗旨是数据传输,而不是显示数据
  3.    xml标签没有被提前定义,须要自行定义标签
  4.    xml被设计为具有自我描写叙述性
  5.    xml是W3C的推荐标准
     xml和html对照:
  •      XML被设计为传输和存储数据,其焦点是数据的内容。
  •      html被设计用来显示数据,其焦点是数据的外观。
  •      html旨在显示信息,而xml旨在传输信息。
演示样例:
<bookstore>
    <book category="CHILDREN">
         <title>harry Potter</title>
         <author>JK.Rowing</author>
         <year>2005</year>
         <price>35.2</price>
    </book>
</bookstore>
元素能够包括其它元素、文本或者两者的混合物。元素也能够拥有属性。
<bookstore>和<book>都拥有元素内容,<author>仅仅有文本内容,<book>还拥有属性。


二、Dom方式读取xml

新建一个java project。在工程根文件夹下放置一个languages.xml:
<?

xml version="1.0" encoding="UTF-8"?> <Languages cat="it"> <lan id="1"> <name>java</name> <ide>Eclipse</ide> </lan> <lan id="2"> <name>Swift</name> <ide>Xcode</ide> </lan> <lan id="3"> <name>C#</name> <ide>Visual Studio</ide> </lan> </Languages>

Dom方式读取xml文件:
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadXml {
	public static void main(String[] args) {
		try {
			// Dom方式
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new File("language.xml"));

			Element root = document.getDocumentElement();
			System.out.println("cat=" + root.getAttribute("cat"));
			NodeList list = root.getElementsByTagName("lan");
			for (int i = 0; i < list.getLength(); i++) {
				Element lan = (Element) list.item(i);
				System.out.println("------------------");
				System.out.println("id=" + lan.getAttribute("id"));

				/*
				 * Element name=(Element)
				 * lan.getElementsByTagName("name").item(0);
				 * System.out.println("name="+name.getTextContent()); Element
				 * ide=(Element) lan.getElementsByTagName("ide").item(0);
				 * System.out.println("ide="+ide.getTextContent());
				 */

				NodeList clist = lan.getChildNodes();
				for (int j = 0; j < clist.getLength(); j++) {
					Node c = clist.item(j);
					if (c instanceof Element) {

						System.out.println(c.getNodeName() + "=" + c.getTextContent());
					}
				}
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

输出:

cat=it
------------------
id=1
name=java
ide=Eclipse
------------------
id=2
name=Swift
ide=Xcode
------------------
id=3
name=C#
ide=Visual Studio

三、Dom方式创建XML

package ucas.yp.xml;

import java.io.File;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXml {
	public static void main(String[] args) {

		try {
			DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document=builder.newDocument();
			
			Element root=document.createElement("Languages");
			root.setAttribute("cat", "it");
			
			Element lan1=document.createElement("lan");
			lan1.setAttribute("id", "1");
			Element name1=document.createElement("name");
			name1.setTextContent("Java");
			Element ide1=document.createElement("ide");
			ide1.setTextContent("Eclipse");
			lan1.appendChild(name1);
			lan1.appendChild(ide1);
			
			
			//从内到外一层层包装
			Element lan2=document.createElement("lan");
			lan2.setAttribute("id", "2");
			Element name2=document.createElement("name");
			name2.setTextContent("Swift");
			Element ide2=document.createElement("ide");
			ide2.setTextContent("Xcode");
			lan2.appendChild(name2);
			lan2.appendChild(ide2);
		
			
			
			Element lan3=document.createElement("lan");
			lan3.setAttribute("id", "3");
			Element name3=document.createElement("name");
			name3.setTextContent("C#");
			Element ide3=document.createElement("ide");
			ide3.setTextContent("Visual Studio");
			lan3.appendChild(name3);
			lan3.appendChild(ide3);
			
			
			root.appendChild(lan1);
			root.appendChild(lan2);
			root.appendChild(lan3);
		    document.appendChild(root);
			
		    TransformerFactory trFactory=TransformerFactory.newInstance();
		    Transformer transformer=trFactory.newTransformer();
		    StringWriter writer=new StringWriter();
		    transformer.transform(new DOMSource(document), new StreamResult(writer));
			//----- 字符串输出
			System.out.println(writer.toString());
			//-----生成xml文件
			transformer.transform(new DOMSource(document), new StreamResult( new File("newxml.xml")));
			
			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
}

四、使用Dom4j操作xml

Dom4j是一个优秀的java操作xml的库,具有性能优异、功能强大和极其易使用的特点。下载地址:http://www.dom4j.org/dom4j-1.6.1/
package ucas.yp.xml;

import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.XMLWriter;

public class TestDom4j {
	public static void main(String[] args) {
		String xmlString = "<bookstore><book><title>harry Potter</title><author>JK.Rowing</author><year>2005</year><price>35.2</price></book></bookstore>";
		try {
			Document document = DocumentHelper.parseText(xmlString);
			// 打印
			System.out.println(document.asXML());

			
			//生成xml文件
			XMLWriter writer = new XMLWriter(new FileWriter("book.xml"));
			writer.write(document);
			writer.close();

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
刷新project文件夹。能够看到新生成的book.xml。





posted @ 2017-07-27 21:27  lytwajue  阅读(324)  评论(0编辑  收藏  举报