当前位置 : 主页 > 编程语言 > c++ >

xml文档内容的获取

来源:互联网 收集:自由互联 发布时间:2021-06-30
gistfile1.txt import java.io.File;import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.jxnd.bean.Role
gistfile1.txt
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jxnd.bean.Roles;
import org.jxnd.bean.UserInfo;

public class TestDemo {
	public static void main(String[] args) throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("src/users.xml"));
		Element root = doc.getRootElement();
		List
 
   list = new ArrayList
  
   (); getUserInfoByXml(root,list); for (UserInfo userInfo : list) { System.out.println(userInfo); } } public static void getUserInfoByXml(Element root,List
   
     list) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ List
    
      elements = root.elements(); for(Element element : elements){ if(element.getName().equals("user")){ UserInfo info = setUserInfo(element); list.add(info); } } } public static UserInfo setUserInfo(Element root){ UserInfo info=new UserInfo(); List
     
       elements=root.elements(); for (Element element : elements) { if (element.getName().equals("id")) info.setId(Integer.parseInt(element.getText())); if (element.getName().equals("name")) info.setName(element.getText()); if (element.getName().equals("pwd")) info.setPwd(element.getText()); if (element.getName().equals("rolesid")) info.setRolesid(Integer.parseInt(element.getText())); if (element.getName().equals("rinfo")) info.setRinfo(getRolesByXml(element)); } return info; } public static Roles getRolesByXml(Element root){ Roles info=new Roles(); List
      
        elements=root.elements(); for (Element element : elements) { if (element.getName().equals("id")) info.setId(Integer.parseInt(element.getText())); if (element.getName().equals("name")) info.setName(element.getText()); } return info; }
      
     
    
   
  
 
Users.xml
 

 
	
   
   
    1
    
   
    ln
    
   
    12345
    
   
    1
    
    
    
     1
     
    
     Boss
     
    
  
	
   
   
    2
    
   
    xq
    
   
    12345
    
   
    2
    
    
    
     2
     
    
     ceo
     
    
  
	
   
   
    3
    
   
    xxx
    
   
    12345
    
   
    3
    
    
    
     3
     
    
     cto
     
    
  
	
   
   
    4
    
   
    lzl
    
   
    12345
    
   
    2
    
    
    
     2
     
    
     ceo
     
    
  
	
   
   
    5
    
   
    nn
    
   
    12345
    
   
    2
    
    
    
     2
     
    
     ceo
     
    
  

 
网友评论