JAvaのxml読み書き

23701 ワード

xml読み出しの基本はxmlファイルの入力ストリームをパラメータとして取得し、いくつかのクラスメソッドでdocumentオブジェクトを返します.(sax読み取りを除く)では、次は簡単です.xmlの書き込みは、出力フォーマットを設定したtransformer変換器を用いてdocumentオブジェクトとxmlファイルの出力ストリームをパラメータとしてxmlドキュメントを生成します.採用したテストxmlは、世界のすべてのレベルの都市を含むxmlドキュメントで、すべての国、州があれば都市を読まない(中国を除く)のロジックでは、ドキュメント全体に3512件の利用可能なデータがあります.ソースコードのダウンロード
一、Dom方式で読み書きする
Dom方式の読み書きは、DocumentBuilderオブジェクトを使用してxmlファイルを読み込むかdocumentオブジェクトを作成し、DocumentBuilderオブジェクトを作成するコードを1つの方法に入れます.
	/**
	 * @Decription TODO   DocumentBuilder  
	 * @date 2016 10 12    8:29:46
	 * @return
	 */
	public  DocumentBuilder getDocumentBuilder(){
		//   DocumentBuilderFactory  
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder db =null;
		try {
			 db= factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return db;
	}

1、Dom読み
すべてのノードを一度にロードすると(xmlファイルが大きすぎると遅い場合があります)、xmlの構造を保存できます(変更が容易で、ツリー全体がメモリに保存されます).DocumentBuilderオブジェクトのparse()メソッドを使用してxmlドキュメントをロードします.
	/**
	 * @Decription TODO
	 *              ,       .
	 * 	              :           state,             city      .
	 *	                  
	 * @date 2016 10 11    2:46:25
	 */
	 public  void  domParseTest() {
		
		try {
			//   DocumentBuilder  
			DocumentBuilder builder = this.getDocumentBuilder();
			//   xml       xml document  ,parse         。               ( ^_^)
			Document document = builder.parse("LocList.xml");
			//         
			NodeList countrys = document.getElementsByTagName("CountryRegion");
			//                 
			int count = 0;
			//    CountryRegion  
			for (int j = 0; j < countrys.getLength(); j++) {
				String countryName = "";
				String countryCode = "";
				//    CountryRegion  
				Element country = (Element) countrys.item(j);
				//        
				if(country.hasAttributes()){
					//            ,             ,           
					countryName = country.getAttribute("Name");
					countryCode = country.getAttribute("Code");
					System.out.println("  :" + countryName + "    :" + countryCode);
					count++;
				}
				//    CountryRegion         
				if (country.hasChildNodes()) {
					//  CountryRegion      
					NodeList states = country.getChildNodes();
					//    CountryRegion      State  
					for (int k = 0; k < states.getLength(); k++) {
						//  city state   name   
						String cityName = "";
						//  city state   code   
						String cityCode = "";
						//          (if)   (else if  else)  elseif    if elseif     ,        if elseif   elseif   。
						if ("State".equals(states.item(k).getNodeName()) && states.item(k).hasAttributes() && "       ".equals(countryName)) {
							if (states.item(k).getNodeType() == Node.ELEMENT_NODE){
								NamedNodeMap stateAttr = states.item(k).getAttributes();
								for (int i = 0; i < stateAttr.getLength(); i++) {
									Attr attr = (Attr) stateAttr.item(i);
									if ("Name".equals(attr.getNodeName())) {
										cityName = attr.getNodeValue();
									} else {
										cityCode = attr.getNodeValue();
									}
								}
								System.out.println(countryName + "   : " + cityName + "    :" + cityCode);
								count++;
								if (states.item(k).hasChildNodes()){
									NodeList cityList = states.item(k).getChildNodes();
									//       
									String curState = cityName;
									for (int city = 0; city < cityList.getLength(); city++) {
										if (cityList.item(city).hasAttributes()){
											NamedNodeMap cityAttr = cityList.item(city).getAttributes();
											for (int i = 0; i < cityAttr.getLength(); i++) {
												Attr attr = (Attr) cityAttr.item(i);
												if ("Name".equals(attr.getNodeName())) {
													cityName = attr.getNodeValue();
												} else {
													cityCode = attr.getNodeValue();
												}
											}
											System.out.println(countryName + curState + "      : " + cityName + "    :" + cityCode);
											count++;
										}
									}
								}
							}
							
						}else if("State".equals(states.item(k).getNodeName()) && states.item(k).hasAttributes() ){
							NamedNodeMap cityAttr = states.item(k).getAttributes();
							for (int i = 0; i < cityAttr.getLength(); i++) {
								Attr attr = (Attr) cityAttr.item(i);
								if ("Name".equals(attr.getNodeName())) {
									cityName = attr.getNodeValue();
								} else {
									cityCode = attr.getNodeValue();
								}
							}
							System.out.println(countryName + "     : " + cityName + "    :" + cityCode);
							count++;
						}else {
							/**
							 *         state   System.out.println(states.item(k).getNodeName());      :
							 * #text  TEXT_NODE
							 * State  ELEMENT_NODE
							 * #text
							 *         
							 **/
							if (states.item(k).getNodeType() == Node.ELEMENT_NODE){
								if(states.item(k).hasChildNodes()){
									NodeList cityList = states.item(k).getChildNodes();
									for (int city = 0; city < cityList.getLength(); city++) {
										if (cityList.item(city).hasAttributes()){
											NamedNodeMap cityAttr = cityList.item(city).getAttributes();
											for (int i = 0; i < cityAttr.getLength(); i++) {
												Attr attr = (Attr) cityAttr.item(i);
												if ("Name".equals(attr.getNodeName())) {
													cityName = attr.getNodeValue();
												} else {
													cityCode = attr.getNodeValue();
												}
											}
											System.out.println(countryName + "     : " + cityName + "    :" + cityCode);
											count++;
										}
									}
								}else{
									NamedNodeMap cityAttr = states.item(k).getAttributes();
									for (int i = 0; i < cityAttr.getLength(); i++) {
										Attr attr = (Attr) cityAttr.item(i);
										if ("Name".equals(attr.getNodeName())) {
											cityName = attr.getNodeValue();
										} else {
											cityCode = attr.getNodeValue();
										}
									}
									System.out.println(countryName + "     : " + cityName + "    :" + cityCode);
									count++;
								}
								
							}
						}
					}
				} else {
					System.out.println(countryName + "     ,      !");
				}
			}
			System.out.println("   :" + count + "   !");
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

2、Dom書き
DocumentBuilderオブジェクトを使用してdocumentオブジェクトを作成し、Transformerオブジェクトはxmlドキュメントを生成します.
/**
	  * dom  xml  
	  */
	public void domCreateXml(){
		//  DocumentBuilder  
		DocumentBuilder db = this.getDocumentBuilder();
		//    Dom 
		Document document =	db.newDocument();
		//  standalone="no"  ,         xml,    DTD(document type definition      )  
		document.setXmlStandalone(true);
		//  Location   
		Element rootElement = document.createElement("Location");
		//  CountryRegion  
		Element country = document.createElement("CountryRegion");
		country.setAttribute("Name", "  ");
		country.setAttribute("Code", "1");
		//  State  
		Element state = document.createElement("State");
		state.setAttribute("Name", "  ");
		state.setAttribute("Code", "22");
		//  city  
		Element city = document.createElement("City");
		city.setAttribute("Name", "  ");
		city.setAttribute("Code", "cd");
		// city state     , city   state 
		state.appendChild(city);
		// state country     , state   country 
		country.appendChild(state);
		// country Location     , state   country 
		rootElement.appendChild(country);
		
		//        rootElement   document 
		document.appendChild(rootElement);
		//      ,       new          
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			//  transformer  
			Transformer transformer = transFactory.newTransformer();
			//    
			transformer.setOutputProperty(OutputKeys.INDENT, "Yes");
			//    ,       ,            ,             。
			transformer.transform(new DOMSource(document), new StreamResult("LocListDom.xml"));
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

二、SAX方式で読み書きする
1、SAX読み
イベント駆動、逐行読み出し、DefaultHandlerを書き換えることで解析されたシーンを取得します.
/**
	 * @Decription TODO
	 * @date 2016 10 12    7:33:26
	 */
	public  void saxParseTest(){
		//SAXParserFactory     
		SAXParserFactory factory  =	SAXParserFactory.newInstance();
		InputStream in = null;
		try {
			//       SAXParser  
			SAXParser parser = factory.newSAXParser();
			//       
			in = new FileInputStream("LocList.xml");
			//  
			parser.parse(in, new SaxHandler());
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(in != null)
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

DefaultHandler書き換えの4つのメソッドを継承して解析状態を取得
package my.sax.practice;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxHandler extends DefaultHandler{
		//  CountryRegion name   
		String countryName = "";
		//  CountryRegion code   
		String countryCode = "";
		//  city state   name   
		String stateName = "";
		//  city state   code   
		String stateCode = "";
		/**
		 * xml    
		 */
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			System.out.println("sax xml    ");
		}
		/**
		 *       
		 */
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			//attributes!=null    
			if(attributes.getLength() > 0){
				switch (qName) {
				case "CountryRegion":
					countryName =  attributes.getValue("Name");
					countryCode =  attributes.getValue("Code");
					System.out.println("  :" + countryName + "    :" + countryCode);
					break;
				case "State":
					stateName =  attributes.getValue("Name");
					stateCode = attributes.getValue("Code");
					System.out.println(countryName + "     : " + stateName + "    :" + stateCode);
					break;	
				case "City":
					String cityName = attributes.getValue("Name");
					String cityCode = attributes.getValue("Code");
					if("".equals(stateName) && "".equals(stateCode)){
						System.out.println(countryName + "     : " + cityName + "    :" + cityCode);
					}else{
						System.out.println(countryName + stateName + "      : " + cityName + "    :" + cityCode);
					}
					break;	
				default:
					break;
				}
			}else{
				if(qName.equals("State")){
					stateName = "";
					stateCode = "";
				}
			}
		}
		/**
		 *       
		 */
		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
		}
		/**
		 * xml    
		 */
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
			System.out.println("sax xml    ");
		}
}

2、SAX書き
/**
	 * @Decription TODO sax      xml  
	 * @date 2016 10 12    8:37:26
	 */
	public void saxCreateXml(){
		//1、    SAXTransformerFactory    
		SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
		OutputStream in =null;
		try {
			//2、  SAXTransformerFactory    TransformerHandler  
			TransformerHandler handler = sf.newTransformerHandler();
			//3、  TransformerHandler    Transformer  (    xml       )
			Transformer transformer = handler.getTransformer();
			//       DTD(Document Type Defination       )  
			transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
			//      ,       
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			//    
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			//    
			File file =new File("LocListSax.xml");
			//  file    
			if(!file.exists()){
				if(!file.createNewFile()){
					throw new FileNotFoundException("      !");
				}
			}
			//4、     OutputStream  
			in = new FileOutputStream(file);
			//5、   Result  
			Result result = new StreamResult(in);
			//6、  result,           (handler     )       (result  )
			handler.setResult(result);
			//    
			handler.startDocument();
			//    
			AttributesImpl attr = new AttributesImpl();
			//      
			handler.startElement("", "", "Location", attr);
			attr.addAttribute("", "", "Name", "", "     ");
			attr.addAttribute("", "", "Code", "", "DZA");
			handler.startElement("", "", "CountryRegion", attr);
			attr.clear();
			attr.addAttribute("", "", "Name", "", "    ");
			attr.addAttribute("", "", "Code", "", "ADR");
			handler.startElement("", "", "State", attr);
			handler.endElement("", "", "State");
			handler.endElement("", "", "CountryRegion");
			//      
			handler.endElement("", "", "Location");
			//    
			handler.endDocument();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	finally{
				try {
					//   ,     ,        
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
				
	}

三、JDom方式で読み書きする
1、JDom読み
public static void jdomParseTest(){
		//  SAXBuilder  
		SAXBuilder builder = new SAXBuilder();
		//  InputStream        null
		InputStream in = null ;
		//  CountryRegion name   
		String countryName = "";
		//  CountryRegion code   
		String countryCode = "";
		//  city state   name   
		String stateName = "";
		//  city state   code   
		String stateCode = "";
		//        
		InputStreamReader reader =null;
		try {
			//        
			in =new FileInputStream("LocList.xml");
			//              
			reader = new InputStreamReader(in, "UTF-8");
			//  SAXBuilder   build    xml Document  
			//  :         ,    :  notepad++ utf-8    
			Document document = builder.build(reader);
			//     Location
			Element rootElement = document.getRootElement();
			//     Location    
			List coutryList = rootElement.getChildren();
			//     
			for(Element country : coutryList){
				if (country.hasAttributes()){
					countryName = country.getAttributeValue("Name");
					countryCode = country.getAttributeValue("Code");
					System.out.println("  :" + countryName + "    :" + countryCode);
					//  country    state
					List stateList = country.getChildren();
					//  state
					for (Element state : stateList){
						//           state         , 
						if(state.hasAttributes()){
							stateName = state.getAttributeValue("Name");
							stateCode = state.getAttributeValue("Code");
							//        state     
							if("       ".equals(countryName)){
								//  state    city
								List cityList = state.getChildren();
								//  city
								for (Element city : cityList){
									if(city.hasAttributes()){
										String cityName = city.getAttributeValue("Name");
										String cityCode = city.getAttributeValue("Code");
										System.out.println(countryName + stateName + "      : " + cityName + "    :" + cityCode);
									}
								}
							}else{
								System.out.println(countryName + "     : " + stateName + "    :" + stateCode);
							}
						}else{
							//  state    city
							List cityList = state.getChildren();
							//  city
							for (Element city : cityList){
								if(city.hasAttributes()){
									String cityName = city.getAttributeValue("Name");
									String cityCode = city.getAttributeValue("Code");
									System.out.println(countryName + "     : " + cityName + "    :" + cityCode);
								}
							}
						}
					}
				}
			}
			
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			
				try {
					if(in !=null)
					in.close();
					if (reader != null)
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

2、JDom書き
/**
	 *jdom    xml  
	 */
	public static void jdomCreateXml(){
		//     
		Element root = new Element("Location");
		//  document  
		Document document = new Document(root);	
		//     
		Element child = new Element("CountryRegion");
		child.setAttribute("Name", "  ");
		child.setAttribute("Code", "1");
		//     
		Element subchild = new Element("State");
		subchild.setAttribute("Name", "  ");
		subchild.setAttribute("Code", "sc");
		//     
		Element subsubchild = new Element("City");
		subsubchild.setAttribute("Name", "  ");
		subsubchild.setAttribute("Code", "cd");
		//      
		subchild.addContent(subsubchild);
		//     
		child.addContent(subchild);
		//    
		root.addContent(child);
		//  Format  ,   xml
		Format formater =Format.getPrettyFormat();
		//  XMLOutputter  
		XMLOutputter outputer = new XMLOutputter(formater);
		//      ,         
		OutputStream out = null;
		//  xml  
		File file = new File("LocListJdom.xml");
		try {
			if (!file.exists()){
					if (!file.createNewFile()){
						throw new FileCanNotCreateException();
					}
			}
			//     
			out = new FileOutputStream(file);
			//XMLOutputter  
			outputer.output(document, out);
		} catch (IOException e) {
			e.printStackTrace();
			e.printStackTrace();
		} catch (FileCanNotCreateException e) {
			e.printStackTrace();
		} finally{
			//   
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

四、Dom 4 j方式で読み書きする
1、Dom 4 j読み
public static void dom4jParseTest(){
		//  CountryRegion name   
		String countryName = "";
		//  CountryRegion code   
		String countryCode = "";
		//  city state   name   
		String stateName = "";
		//  city state   code   
		String stateCode = "";
		//  InputStream        null
		InputStream in = null;
		SAXReader reader = new SAXReader();
		//          
		InputStreamReader isr =null;
		try {
			in =new FileInputStream("LocList.xml");
			//            
			isr = new InputStreamReader(in, "UTF-8");
			//  read         SAXBuilder   xml Document  
			Document document = reader.read(isr);
			//     Location
			Element rootElement = document.getRootElement();
			//     Location    
			@SuppressWarnings("unchecked")
			List coutryList = rootElement.elements();
			//     
			for(Element country : coutryList){
				if (country.attributes()!=null && country.attributes().size()>0){
					countryName = country.attributeValue("Name");
					countryCode = country.attributeValue("Code");
					System.out.println("  :" + countryName + "    :" + countryCode);
					//  country    state
					@SuppressWarnings("unchecked")
					List stateList = country.elements();
					//  state
					for (Element state : stateList){
						//           state         , 
						if(state.attributes()!=null && state.attributes().size()>0){
							stateName = state.attributeValue("Name");
							stateCode = state.attributeValue("Code");
							//        state     
							if("       ".equals(countryName)){
								//  state    city
								@SuppressWarnings("unchecked")
								List cityList = state.elements();
								//  city
								for (Element city : cityList){
									if(city.attributes()!=null && city.attributes().size()>0){
										String cityName = city.attributeValue("Name");
										String cityCode = city.attributeValue("Code");
										System.out.println(countryName + stateName + "      : " + cityName + "    :" + cityCode);
									}
								}
							}else{
								System.out.println(countryName + "     : " + stateName + "    :" + stateCode);
							}
						}else{
							//  state    city
							@SuppressWarnings("unchecked")
							List cityList = state.elements();
							//  city
							for (Element city : cityList){
								if(city.attributes()!=null && city.attributes().size()>0){
									String cityName = city.attributeValue("Name");
									String cityCode = city.attributeValue("Code");
									System.out.println(countryName + "     : " + cityName + "    :" + cityCode);
								}
							}
						}
					}
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (DocumentException e) {
			e.printStackTrace();
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally{
			//   
			try {
				if(in != null)
					in.close();
				if (isr != null)
					isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}

2、Dom 4 j書き
/**
	 *   xml  
	 */
	public static void Dom4jCreateXml(){
		//      
		OutputStream out = null;
		//  DocumentHelper  document  
		Document document = DocumentHelper.createDocument();
		//     
		Element root = document.addElement("Location");
		//     
		Element child =root.addElement("CountryRegion");
		child.addAttribute("Name", "  ");
		child.addAttribute("Code", "1");
		//     
		Element subchild = child.addElement("State");
		subchild.addAttribute("Name", "  ");
		subchild.addAttribute("Code", "sc");
		//     
		Element subsubchild = subchild.addElement("City");
		subsubchild.addAttribute("Name", "  ");
		subsubchild.addAttribute("Code", "cd");
		//     
		try {
			//     
			out = new FileOutputStream("LocListDom4j.xml");
			//createPrettyPrint   xml     OutPutFormat  
			OutputFormat of = OutputFormat.createPrettyPrint();
			//    XMLWriter  
			XMLWriter writer = new XMLWriter(out,of);
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

五、四方式の性能比較
4つの方法の中でsaxの読み書きが一番速いですが、saxは読み返すことができません.dom 4 jは2番目に重要なコード量が少ないですね.実際の応用は多いです(springはdom 4 jを使っています).jdomもdomも差が少なく、domの性能はもっといいです(何回もテストしたことがありませんが、目測).