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

<students> 
<student sn="01">		
<name>张三</name> 
		<age>18</age> 
</student>  	
<student sn="02" > 	<name>李四</name> 		<age>20</age> 	</student>
<student sn="03" > 	<name>王五</name> 		<age>22</age> 	</student>
</students>


结果:convert.xml



<?xml version="1.0" encoding="UTF-8"?>

<students> 
<student desc="好样的" sn="01">		
<name>张三</name> 
		<age>100</age> 
</student>  	
<student sn="02"> 	
  <name>李四</name> 		
  <age>20</age> 	
</student>
<student sn="03"> 	
   <name>王五</name> 		
    <age>22</age> 	
</student>
<student sn="04"><name>王五</name><age>26</age></student>
</students>



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
<students xmlns:stu="http://www.cs.com/student">
	<student sn="01">
		
		<stu:age>18</stu:age>
		<name>张三</name>
	</student>
	
	<student sn="01">
		
		<stu:age>20</stu:age>
		<name>里斯</name>
	</student>
</students>


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


-*****************************************************-
<?xml version="1.0" encoding="UTF-8"?>
<InitDatas>
	<Modules>
	    <Module name="信息管理" sn="xxgl" url="" orderNo="1000" >
			<Module name="公告信息" sn="news" url="news.do" orderNo="1001"/>
			<Module name="发布公告" sn="employee" url="news.do" orderNo="1002"/>
		</Module>	 
		<Module name="系统管理" sn="xtgl" url="" orderNo="2000"  >
			<Module name="帐号信息" sn="user" url="user.do?deptId=0" orderNo="2001" visible="false" />
			<Module name="角色信息" sn="role" url="role.do?deptId=0" orderNo="2002"/>
			<Module name="模块信息" sn="module" url="module.do?deptId=0" orderNo="2003"/>
		</Module>
		<Module name="教师管理" sn="jsgl" url="" orderNo="3000"  >
			<Module name="作业信息" sn="taskinfo" url="student.do" orderNo="3001" visible="false" />
			<Module name="发布作业任务" sn="homeworkinfo" url="task.do?method=makehome" orderNo="3002"  />
			<Module name="已发布的作业" sn="homeworkmaked" url="task.do?method=haveMaked" orderNo="3003"  />
		</Module>
		<Module name="学生管理" sn="xsgl" url="" orderNo="4000"  >
			<Module name="作业成绩" sn="student" url="student.do?method=lookScore" orderNo="4001" visible="false" />
			<Module name="作业提交记录" sn="homehistory" url="student.do?method=homehistory" orderNo="4002"  />
			<Module name="查看作业任务" sn="hometask" url="student.do?method=looktask" orderNo="4003"  />
			<Module name="资源共享区" sn="share" url="task.do?method=share" orderNo="4004"  />
			
		</Module>
		<Module name="个人系统管理" sn="sytemmgr" url="" orderNo="5000">
			<Module name="密码修改" sn="chgpsw" url="user.do?method=chgpsw" orderNo="5001"/>
			<Module name="查看个人信息" sn="selfInfof" url="student.do?method=selfInfo" orderNo="5002"/>
			<Module name="系统初始化" sn="systeminit" url="systeminit.do" orderNo="5003"/>
		</Module>		 
	</Modules>	 
</InitDatas>



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;
	}
	
}

你可能感兴趣的:(java,thread,xml)