Java針對XML檔案的操作大集合

XML是工作上常用到的資料交換格式,會需要利用JAVA進行XML資料的新增、修改或刪除,這裡把相關的方法記錄下來。

下述範例會存取在C:\Projects\Javas\中的sample.xml檔,而檔案中已經有以下的內容:

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

<root> 
  <item> 
    <productID>10001</productID>  
    <productName>產品名稱1</productName>  
    <productPrice>10</productPrice> 
  </item>
  <item> 
    <productID>10002</productID>  
    <productName>產品名稱2</productName>  
    <productPrice>20</productPrice> 
  </item>  
  <item> 
    <productID>10003</productID>  
    <productName>產品名稱3</productName>  
    <productPrice>30</productPrice> 
  </item>
</root>

利用Java存取XML我選用的Library是dom4j,可參考官網的介紹,以下是JAVA存取的程式範例:

package CDIT.stanley;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

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


public class dom4jXMLFullSample {
	
	//新增XML Node內容
	public static String XMLAppendNode(String xmlFilePath, String productID, String productName, String productPrice){
		
		String appendStatus = "0";
		
		try {
			
			SAXReader reader = new SAXReader();
			Document document = reader.read(xmlFilePath);
			Element root = document.getRootElement();
			Element item = root.addElement("item");
			
			item.addElement("productID").setText(productID);
			item.addElement("productName").setText(productName);
			item.addElement("productPrice").setText(productPrice);
			
			OutputFormat format = OutputFormat.createPrettyPrint();
		    format.setEncoding("utf-8");
		    XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format);
		    writer.write(document);
		    writer.close();
		    appendStatus = "1";
			
		} catch (DocumentException e) {
			return appendStatus;
		} catch (UnsupportedEncodingException e) {
			return appendStatus;
		} catch (FileNotFoundException e) {
			return appendStatus;
		} catch (IOException e) {
			return appendStatus;
		}
		return appendStatus;
			
	}
	
	//修改XML Node內容
	public static String XMLChangeNodeValue(String xmlFilePath, String productID, String productName, String productPrice){
		
		String updateStatus = "0";
		
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(xmlFilePath);
			Element root = document.getRootElement();
			@SuppressWarnings("rawtypes")
			Iterator it = root.elementIterator();
	        
			while (it.hasNext()) {
	            Element element = (Element) it.next();	            
	            if(productID.equals(element.elementText("productID"))){	            	
	    		    try {
	    		    	
		            	element.element("productName").setText(productName);
		            	element.element("productPrice").setText(productPrice);
		            	
		            	OutputFormat format = OutputFormat.createPrettyPrint();
		    		    format.setEncoding("utf-8");
		    		    XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format);
						writer.write(document);
						writer.close();
						updateStatus = "1";
					} catch (IOException e) {
						return updateStatus;
					}	    		   
				}
	        }
			return updateStatus;
		} catch (DocumentException e) {
			return updateStatus;
		}

	}
	
	//刪除XML Node
	public static String XMLRemoveNode(String xmlFilePath , String productID){
		String removeStatus = "0";
		
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(xmlFilePath);
			Element root = document.getRootElement();
			@SuppressWarnings("rawtypes")
			Iterator it = root.elementIterator();
	        
			while (it.hasNext()) {
	            Element element = (Element) it.next();
	            if(productID.equals(element.elementText("productID"))){  	
	    		    try {
		            	element.element("item");
		            	element.detach();
		            	
		            	OutputFormat format = OutputFormat.createPrettyPrint();
		    		    format.setEncoding("utf-8");
		    		    XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format);
						writer.write(document);
						writer.close();
						removeStatus = "1";
					} catch (IOException e) {
						return removeStatus;
					}
				}	            
	        }
			return removeStatus;
		} catch (DocumentException e) {
			return removeStatus;
		}

	}
	
	public static void main (String[] args){
		String xmlFilePath = "C:\\Projects\\Javas\\sample.xml";
		//新增
		XMLAppendNode(xmlFilePath , "10004", "產品名稱4", "40");
		//修改
		XMLChangeNodeValue (xmlFilePath , "10001", "測試修改", "100");
		//刪除
		XMLRemoveNode (xmlFilePath , "10002");
	}
}

上述程式進行完後,會將原本的XML檔變成如下的內容:

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

<root> 
  <item> 
    <productID>10001</productID>  
    <productName>測試修改</productName>  
    <productPrice>100</productPrice> 
  </item>  
  <item> 
    <productID>10003</productID>  
    <productName>產品名稱3</productName>  
    <productPrice>30</productPrice> 
  </item>  
  <item> 
    <productID>10004</productID>  
    <productName>產品名稱4</productName>  
    <productPrice>40</productPrice> 
  </item> 
</root>

You may also like...

7,821 Responses

  1. PatrickLef表示:

    farmaci senza ricetta elenco: Cialis generico 5 mg prezzo – acquisto farmaci con ricetta

  2. MichaelToP表示:

    Farmacia online piГ№ conveniente Farmacia online migliore migliori farmacie online 2024

  3. Kennethtub表示:

    http://brufen.pro/# Ibuprofene 600 prezzo senza ricetta
    farmacia online piГ№ conveniente

  4. betthaizone表示:

    Pretty! This has been a really wonderful post. Many thanks for supplying this information.

  5. PatrickLef表示:

    farmacia online: Cialis generico 5 mg prezzo – farmacia online

  6. Edgarappow表示:

    viagra online spedizione gratuita: miglior sito per comprare viagra online – alternativa al viagra senza ricetta in farmacia

  7. What’s The Job Market For Double Glazing Repairs Near Me Professionals
    Like? Double glazing repairs near me

  8. сервисный центре предлагает ремонт телевизоров самсунг на дому москва – ремонт телевизоров на дому в москве

  9. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт бытовой техники в ростове на дону
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. [url=https://remont-kondicionerov-wik.ru]сколько стоит ремонт кондиционера[/url]

  11. Denniskew表示:

    SpaceX Polaris Dawn crew returns home after history-making mission
    раз анальный секс

    SpaceX’s Polaris Dawn crew is home, capping off a five-day mission to orbit — which included the world’s first commercial spacewalk — by splashing down in the Gulf of Mexico.

    The Crew Dragon capsule carrying four astronauts landed off the coast of Dry Tortugas, Florida, at 3:37 a.m. ET Sunday.
    The Polaris Dawn mission made history as it reached a higher altitude than any human has traveled in five decades. A spacewalk conducted early Thursday morning also marked the first time such an endeavor has been completed by a privately funded and operated mission.

    But returning to Earth is among the most dangerous stretches of any space mission.

    To safely reach home, the Crew Dragon capsule carried out what’s called a “de-orbit burn,” orienting itself as it prepared to slice through the thickest part of Earth’s atmosphere.
    The spacecraft then reached extremely hot temperatures — up to 3,500 degrees Fahrenheit (1,900 degrees Celsius) — because of the pressure and friction caused by hitting the air while still traveling around 17,000 miles per hour (27,000 kilometers per hour). The crew, however, should have remained at comfortable temperatures, protected by the Crew Dragon’s heat shield, which is located on the bottom of the 13-foot-wide (4-meter-wide) capsule.

    Dragging against the air began to slow the vehicle down before the Crew Dragon deployed parachutes that further decelerated its descent.

  12. Richardral表示:

    farmacia online piГ№ conveniente Farmacia online piu conveniente farmacia online

  13. PatrickLef表示:

    Farmacia online miglior prezzo: Ibuprofene 600 generico prezzo – farmacia online

  14. MichaelToP表示:

    farmacia online senza ricetta Farmacie on line spedizione gratuita п»їFarmacia online migliore

  15. Cryptoboss Casino: место, где рождаются победители
    cryptoboss официальное зеркало сайт cryptoboss официальный сайт .

  16. MichaelToP表示:

    п»їFarmacia online migliore Cialis generico recensioni farmacia online senza ricetta

  17. Thanks for all your valuable labor on this web site. My mum loves participating in investigation and it’s really obvious why. A number of us notice all of the powerful mode you convey invaluable guidelines by means of the web site and even increase participation from website visitors on that topic so our own princess is without question understanding a lot. Take advantage of the rest of the year. You have been doing a stunning job.

  18. I happen to be writing to make you know of the great experience my friend’s daughter found using the blog. She came to understand a wide variety of details, not to mention how it is like to possess an incredible teaching character to get other folks just have an understanding of selected specialized subject areas. You undoubtedly exceeded visitors’ expectations. I appreciate you for imparting these important, safe, informative and in addition fun tips on your topic to Sandra.

  19. Kennethtub表示:

    https://farmaciait.men/# comprare farmaci online all’estero
    farmacia online senza ricetta

  20. well of course, everyone loves to get rich but not everyone would love to do hard work“

  21. PatrickLef表示:

    farmaci senza ricetta elenco: BRUFEN 600 prezzo in farmacia – top farmacia online

  22. Edgarappow表示:

    comprare farmaci online all’estero: Farmacie online sicure – acquisto farmaci con ricetta

  23. I went over this web site and I conceive you have a lot of great info , saved to my bookmarks (:.

  24. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт крупногабаритной техники в ростове на дону
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  25. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи уфа

  26. Taps表示:

    Nice post, I wonder when crosby will be back. He has been injured for so long now.

  27. Richardral表示:

    top farmacia online farmacia online migliore Farmacie on line spedizione gratuita

  28. MichaelToP表示:

    Farmacia online piГ№ conveniente Farmacie on line spedizione gratuita farmacie online autorizzate elenco

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。