xml解析

阅读更多
只是供自己参考 


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.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;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class DomDML {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance() ;
		
		try {
			DocumentBuilder db = dbf.newDocumentBuilder() ;
			
			Document dom = db.parse(new File("students.xml")) ;
			
			Element eleStu = dom.createElement("student") ;
			
			//eleStu.set
			eleStu.setAttribute("sn", "04") ;
	System.out.print("sn = "+eleStu.getAttribute("sn")) ;
			
			Element eleName = dom.createElement("name") ;
			Element eleAge = dom.createElement("age") ;
			
			Text textName = dom.createTextNode("王五") ;
			Text textAge = dom.createTextNode("26") ;
			
			eleName.appendChild(textName) ;
			eleAge.appendChild(textAge) ;
			
			eleStu.appendChild(eleName) ;
			eleStu.appendChild(eleAge) ;
		
			
			Element root = dom.getDocumentElement() ;
			
			root.appendChild(eleStu) ;
			
			
			Element stuNode = (Element)root.getElementsByTagName("student").item(0) ;
			stuNode.setAttribute("desc", "好样的") ;
			Node nodeAge = stuNode.getElementsByTagName("age").item(0) ;
			
			nodeAge.getFirstChild().setNodeValue("100") ;
			
			TransformerFactory tf = TransformerFactory.newInstance() ;
			Transformer tfr = tf.newTransformer() ;
			
			DOMSource domSource = new DOMSource(dom) ;
			
			StreamResult result = new StreamResult(new File("convert.xml")) ;
			
			tfr.transform(domSource, result) ;
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}

student.xml

 
		
张三 
		18 
  	
 	李四 		20 	
 	王五 		22 	


结果:convert.xml





 
		
张三 
		100 
  	
 	
  李四 		
  20 	

 	
   王五 		
    22 	

王五26




import java.io.File;
import java.io.IOException;
import java.util.Stack;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxFirst extends DefaultHandler  {

	

	
	Stack stack = new Stack() ;
	
	
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {

		if (!stack.empty()){
			 
				String tag = (String)stack.pop() ;
			 
		}
		
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		// TODO Auto-generated method stub
	        if (!stack.empty() && "name".equals(stack.peek())){
	        	System.out.println(new String(ch,start,length));
	        }
		 
	}

	@Override
	public void error(SAXParseException e) throws SAXException {
		System.out.println( "[error]"+ e.getException().getMessage()) ;
	}

	@Override
	public void fatalError(SAXParseException e) throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("[fatalError]"+e.getException().getMessage());
	}

	@Override
	public void warning(SAXParseException arg0) throws SAXException {
		// TODO Auto-generated method stub
		super.warning(arg0);
	}

	
	
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		 System.out.println("stack : " + stack.size() + "  " + stack.toString());
		
		 if (!stack.empty()){
			 stack.push(qName) ;
			 return ;
		 }
		
		 if (qName.equals("student")){
			   
			 if ("01".equalsIgnoreCase(attributes.getValue("sn"))){
				 stack.push(qName) ; 
			 }
			 
			 
		 }
		  
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		SAXParserFactory spf = SAXParserFactory.newInstance() ;
		
		
		try {
			spf.setFeature("http://xml.org/sax/features/namespaces", true) ;
		
			spf.setValidating(true) ;
			
			SAXParser saxParser = spf.newSAXParser() ;
			
			saxParser.parse(new File("studenttests.xml"), new SaxFirst()) ;
			
		} catch (SAXNotRecognizedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

	}

}


studenttests.xml

	
		
		18
		张三
	
	
	
		
		20
		里斯
	


结果:
stack : 0  []
stack : 0  []
stack : 1  [student]
stack : 1  [student]
张三
stack : 0  []
stack : 1  [student]
stack : 1  [student]
里斯


-*****************************************************-


	
	    
			
			
			 
		
			
			
			
		
		
			
			
			
		
		
			
			
			
			
			
		
		
			
			
			
				 
		 




import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.cs.model.Module;
import com.cs.util.SystemException;

public class InitModules {
	
	private ModuleMgr moduleMgr ;
	
	public void initDatas(String xmlFilePath) {
		
		try {
			Document doc = new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFilePath)) ;
			List modules = doc.selectNodes("//Modules/Module") ;
			addModules(modules , null ) ;
		
		} catch (DocumentException e) {
			 
			e.printStackTrace();			
			throw new SystemException("初始化模块数据异常") ;
		}
		
	}
	
	public void addModules(List modules,Module parent) {
		for (int i = 0 ; i < modules.size() ; i++ ) {
			Element element = (Element)modules.get(i) ;
			Module m = new Module() ;
			m.setName(element.attributeValue("name")) ;
			m.setOrderNo(Integer.parseInt(element.attributeValue("orderNo"))) ;
			m.setParent(parent) ;
			m.setSn(element.attributeValue("sn")) ;
			m.setUrl(element.attributeValue("url")) ;
			String strVisible = element.attributeValue("visible") ;
			boolean visible = true ;
			if ("false".equalsIgnoreCase(element.attributeValue("visible"))){
				visible = false ;
			}
			System.out.println(m.getName());
			m.setVisible(visible) ;
		 		
			moduleMgr.addModule(m) ;
			
			addModules(element.selectNodes("Module"),m) ;
			
			
		}
	}

	public void setModuleMgr(ModuleMgr moduleMgr) {
		this.moduleMgr = moduleMgr;
	}
	
}

你可能感兴趣的:(XML,Java,thread)