使用JDOM2.0.4 操作/解析xml


一、解析xml內容

xml文件內容:

<?xml version="1.0" encoding="utf-8"?>
<RETVAL success='true'>
<Shop><sid>1</sid><name>北京鑫和易通貿易有限公司</name></Shop>
<Shop><sid>2</sid><name>張家口市金九福汽車服務有限公司</name></Shop>
</RETVAL>

 

解析的java代碼

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

public Class Test{

public static List test() throws Exception{
  List result = new ArrayList();

  SAXBuilder builder = new SAXBuilder();
  StringReader read = new StringReader(xmlDoc);
  InputSource source = new InputSource(read);
  Document document = builder.build(source);
  Element root = document.getRootElement();// 獲得根節點
  String ifSuccess = root.getAttributeValue("success");
  if (!"true".equals(ifSuccess)) {// 不成功直接返回
      throw new Exception("從接口獲取全部經銷商數據時不成功!");
  }

  List<Element> childrenList = root.getChildren();
  for (Element e : childrenList) {
       Map elementMap = new HashMap<String, String>();
       elementMap.put("sid", e.getChildText("sid")); // 經銷商id
       elementMap.put("name", e.getChildText("name")); // 經銷商名稱
            
       result.add(elementMap);
   }
        
   return result;
  }
}

 


 

二、解析和操作xml文件

xml文件內容

<?xml version="1.0" encoding="UTF-8"?>
<root>
 <person id="1">
  <username>張三</username>
  <password>123123</password>
 </person>
 <person id="2">
  <username>1111111112</username>
  <password>password2</password>
 </person>
</root>

 

JDOM構建document對象的方法

Document    build(java.io.File file)       //This builds a document from the supplied filename.
Document    build(org.xml.sax.InputSource in)   //This builds a document from the supplied input source.
Document    build(java.io.InputStream in)    //This builds a document from the supplied input stream.
Document    build(java.io.InputStream in, java.lang.String systemId)   //This builds a document from the supplied input stream.
Document    build(java.io.Reader characterStream)   //This builds a document from the supplied Reader.
Document    build(java.io.Reader characterStream, java.lang.String systemId)  //This builds a document from the supplied Reader.
Document    build(java.lang.String systemId)  //This builds a document from the supplied URI.
Document    build(java.net.URL url)   //This builds a document from the supplied URL.

 

解析、新增、修改、刪除xml節點屬性的java

package test;

import java.io.FileWriter;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class Test {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        SAXBuilder builder = new SAXBuilder();
        //Document doc = builder.build(new File("src/test.xml"));
        //Document doc = builder.build(new FileInputStream("src/test.xml"));
        //Document doc = builder.build(new FileReader("src/test.xml"));
        //Document doc = builder.build(new URL("http://localhost:8080/jdomTest/test.xml"));
        Document doc = builder.build("src/test.xml");
        
        
        //readXmlFile(doc);
        //addXmlElement(doc);
        //updateXmlElement(doc);
        deleteXmlElement(doc);
    }

    /**
     * 解析xml文件
     * @throws Exception
     */
    public static void readXmlFile(Document doc) throws Exception {
    
        Element root = doc.getRootElement(); //獲取根元素
        
        System.out.println("---獲取第一個子節點和子節點下面的節點信息------");
        Element e = root.getChild("person"); //獲取第一個子元素
        System.out.println("person的屬性id的值:"+e.getAttributeValue("id")); //獲取person的屬性值
        for(Element el: e.getChildren()){
            System.out.println(el.getText());//第一次輸入張三  第二次輸出123123
            System.out.println(el.getChildText("username"));//這里這么寫會是null
            System.out.println(el.getChildText("password"));//這里這么寫會是null
        }
        
        System.out.println("---直接在根節點下就遍歷所有的子節點---");
        for(Element el: root.getChildren()){
            System.out.println(el.getText());//這里輸出4行空格
            System.out.println(el.getChildText("username"));//輸出張三   & 1111111112
            System.out.println(el.getChildText("password"));//輸出123123 &  password2
        }
    }
    
    /**
     * 新增節點
     * @throws Exception
     */
    public static void addXmlElement(Document doc) throws Exception {
        Element root = doc.getRootElement(); //獲取根元素
        
        Element newEle = new Element("person");//設置新增的person的信息
        newEle.setAttribute("id","88888");
        
        Element chiledEle = new Element("username"); //設置username的信息
        chiledEle.setText("addUser");
        newEle.addContent(chiledEle);
        
        Element chiledEle2 = new Element("password"); //設置password的信息
        chiledEle2.setText("addPassword");
        newEle.addContent(chiledEle2);
        
        root.addContent(newEle);
        
        
        XMLOutputter out = new XMLOutputter();
        out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//設置UTF-8編碼,理論上來說應該不會有亂碼,但是出現了亂碼,故設置為GBK
        out.output(doc, new FileWriter("src/test.xml")); //寫文件
    }
    
    /**
     * 更新節點
     * @param doc
     * @throws Exception
     */
    public static void updateXmlElement(Document doc) throws Exception {
        Element root = doc.getRootElement(); //獲取根元素
        
        //循環person元素並修改其id屬性的值
        for(Element el : root.getChildren("person")){
            el.setAttribute("id","haha");
        }
        //循環設置username和password的文本值和添加屬性
        for(Element el: root.getChildren()){
            el.getChild("username").setAttribute("nameVal", "add_val").setText("update_text"); 
            el.getChild("password").setAttribute("passVal", "add_val").setText("update_text"); 
        }
        
        XMLOutputter out = new XMLOutputter();
        out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//設置UTF-8編碼,理論上來說應該不會有亂碼,但是出現了亂碼,故設置為GBK
        out.output(doc, new FileWriter("src/test.xml")); //寫文件
    }
    
    /**
     * 刪除節點和屬性
     * @param doc
     * @throws Exception
     */
    public static void deleteXmlElement(Document doc) throws Exception {
        Element root = doc.getRootElement(); //獲取根元素
        
        List<Element> personList = root.getChildren("person");
        
        //循環person元素,刪除person的id為1的id屬性以及username子節點
        for(Element el : personList){
            if(null!=el.getAttribute("id") && "1".equals(el.getAttribute("id").getValue())){
                el.removeAttribute("id");
                el.removeChild("username");
            }
        }
        
        //循環person元素,刪除person的id為2的節點
        for(int i=0; i<personList.size(); i++){
            Element el = personList.get(i);
            if(null!=el.getAttribute("id") &&  "2".equals(el.getAttribute("id").getValue())){
                root.removeContent(el);//從root節點上刪除該節點
                //警告:此處刪除了節點可能會使personList的長度發生變化而發生越界錯誤,故不能寫成for(int i=0,len=personList.size(); i<len; i++)
            }
        }

        XMLOutputter out = new XMLOutputter();
        out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//設置UTF-8編碼,理論上來說應該不會有亂碼,但是出現了亂碼,故設置為GBK
        out.output(doc, new FileWriter("src/test.xml")); //寫文件
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM