XML 文件读写 自己

来源:互联网 发布:美国华人医师网络医院 编辑:程序博客网 时间:2024/05/24 03:34

1.DOM

import java.io.File;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Source;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.DOMResult;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class DOMTest {public void XMLParser(){DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();try {DocumentBuilder db=dbf.newDocumentBuilder();Document document=db.parse("books.xml");NodeList nodes=document.getElementsByTagName("book"); //节点集合for(int i=0;i<nodes.getLength();i++){Node book=nodes.item(i);NamedNodeMap atts= book.getAttributes(); //属性集合for(int j=0;j<atts.getLength();j++){System.out.println(" 属性名:"+atts.item(j).getNodeName()+" 属性值:"+atts.item(j).getNodeValue());}NodeList childNodes=book.getChildNodes();  //子节点集合for(int k=0;k<childNodes.getLength();k++){if(childNodes.item(k).getNodeType()==Node.ELEMENT_NODE)System.out.println(" 节点名:"+childNodes.item(k).getNodeName()+" 节点值:"+childNodes.item(k).getFirstChild().getNodeValue());}}} catch (ParserConfigurationException e) {e.printStackTrace();}catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void XMLWriter(){DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();try {DocumentBuilder db=dbf.newDocumentBuilder();Document document=db.newDocument();document.setXmlStandalone(true);Element rootElement= document.createElement("bookstore");Element book= document.createElement("book");book.setAttribute("id", "1");rootElement.appendChild(book);document.appendChild(rootElement);TransformerFactory tff=TransformerFactory.newInstance();try {Transformer tf = tff.newTransformer();tf.transform(new DOMSource(document), new StreamResult(new File("books1.xml")));} catch (TransformerConfigurationException e) {e.printStackTrace();}catch (TransformerException e) {e.printStackTrace();}} catch (ParserConfigurationException e) {e.printStackTrace();}}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubDOMTest dom=new DOMTest();dom.XMLParser();dom.XMLWriter();}}

2.JDOM

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import org.jdom2.Attribute;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;public class JDOMTest {public void XMLParser(){SAXBuilder builder =new SAXBuilder();try {InputStreamReader isr = new InputStreamReader(new FileInputStream("books.xml"), "UTF-8");Document document=builder.build(isr);Element rootElement= document.getRootElement();  //根节点List<Element> nodes=rootElement.getChildren();  //节点for(Element node:nodes){List<Attribute> atts=node.getAttributes();  //属性集合for(Attribute att:atts){System.out.println("属性名:"+att.getName()+" 属性值:"+att.getValue());}List<Element> childNodes=node.getChildren();  //子节点集合for(Element child:childNodes){System.out.println("节点名:"+child.getName()+" 节点值:"+child.getValue());}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void XMLCreate(){//1.生成一个根节点Element rss = new Element("rss");rss.setAttribute("version","2.0");Document document=new Document(rss);Element book=new Element("book");Element title = new Element("title");title.setText("<![CDATA[上海移动互联网产业促进中心正式揭牌 ]]>");book.addContent(title);rss.addContent(book);Format format=Format.getCompactFormat();format.setIndent("");format.setEncoding("GBK");//4.创建XMLOutputter的对象XMLOutputter outputer = new XMLOutputter(format);try {outputer.output(document, new OutputStreamWriter(new FileOutputStream("books2.xml")));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {JDOMTest test=new JDOMTest();test.XMLParser();test.XMLCreate();}}

3.DOM4J

import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.util.Iterator;import java.util.List;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class DOM4JTest {public void XMLParser(){SAXReader reader=new SAXReader();    try {Document  document = reader.read(new File("books.xml"));Element rootElement =document.getRootElement();  //根节点Iterator it=rootElement.elementIterator(); //属性while(it.hasNext()){Element  book=(Element)it.next();List<Attribute> atts=book.attributes();for(Attribute att:atts){System.out.println("属性名: "+att.getName()+" 属性值:"+att.getValue());}Iterator itt=book.elementIterator(); //节点while(itt.hasNext()){Element  child=(Element)itt.next();System.out.println("节点名: "+child.getName()+" 节点值:"+child.getText());}}} catch (DocumentException e) {e.printStackTrace();}}public void XMLCreate(){//1.创建document对象,代表整个xml文档          Document document = DocumentHelper.createDocument();       //2.创建根节点rss          Element rss=document.addElement("rss");        rss.addAttribute("version", "2,0");        Element book=rss.addElement("book");        book.setText("安徒生");                //5.设置生成xml的格式          OutputFormat format=OutputFormat.createPrettyPrint();        format.setEncoding("gbk");                File file=new File("books3.xml");        try {FileOutputStream fileout=new FileOutputStream(file);XMLWriter writer=new XMLWriter(fileout);writer.setEscapeText(true);//设置是否转义writer.write(document);} catch (FileNotFoundException e1) {e1.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}                               }/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubDOM4JTest test=new DOM4JTest();test.XMLParser();test.XMLCreate();}}



0 0
原创粉丝点击