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...

10,444 Responses

  1. Barrybib表示:

    order viagra: Sildenafil 100mg price – Cheap Sildenafil 100mg

  2. RogerFaf表示:

    https://fastpillsformen.com/# sildenafil online

  3. BrettTIT表示:

    ed meds on line: fast pills easy – get ed meds today

  4. RogerFaf表示:

    https://fastpillsformen.com/# Cheap Viagra 100mg

  5. RogerFaf表示:

    https://fastpillseasy.com/# erection pills online

  6. BrettTIT表示:

    ed rx online: fast pills easy – ed meds by mail

  7. The 10 Most Terrifying Things About Birmingham
    Double Glazing birmingham double Glazing (hikvisiondb.Webcam)

  8. Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  9. Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  10. RogerFaf表示:

    https://fastpillsformen.com/# buy Viagra online

  11. BrettTIT表示:

    ed medicines online: cheap cialis – pills for erectile dysfunction online

  12. Donaldabula表示:

    online ed medications cheap cialis erectile dysfunction meds online

  13. Donaldabula表示:

    where to get ed pills ed drugs online best online ed treatment

  14. RogerFaf表示:

    https://fastpillsformen.com/# Buy generic 100mg Viagra online

  15. Barrybib表示:

    cheap viagra: Fast Pills For Men – sildenafil 50 mg price

  16. Eliasskype表示:

    vindecoder.expert gmc vin lookup

  17. FOSIL4D表示:

    FOSIL4D merupakan daftar peringkat 1 teratas Bandar Toto Macau terbaik di indonesia dengan permbayaran sudah di jamin amanah dalam hal pembayaran nya mau pun saat melakukan deposit dan para
    pemain juga tidak perlu takut akan hal dalam bertransaksi di situs FOSIL4D karna sudah terjamin keamanan nya.

    Selaku Menjadi daftar peringkat 1 teratas Bandar Toto Macau yang terbesar dan terbaik di Indonesia sangat memperhatikan sistem keamanan dalam melakukan transaksi di
    seluruh games yang tersedia agar para penikmat games selalu dapat bermain dengan tenang dan pastinya aman saat bermain tanpa perlua memikirkan prihal bertransaksi.

    Depo Cuman 10 Ribu Aja

    UDAH BISA DAPAT SCATTER BERUNTUN!!!

  18. BrettTIT表示:

    generic sildenafil: buy viagra online – Generic Viagra online

  19. Charlesbot表示:

    http://fastpillsformen.com/# cheapest viagra

  20. RogerFaf表示:

    https://maxpillsformen.com/# Tadalafil price

  21. BruceGaf表示:

    auto bid master mercury lookup by vin
    mg vin decoder

  22. Bart表示:

    Buzzwords De-Buzzed: 10 Other Ways To Say Buy Driving License
    Online köp Sverige körkort (Bart)

  23. RogerFaf表示:

    http://maxpillsformen.com/# Generic Cialis without a doctor prescription

  24. Barrybib表示:

    buy cialis pill: Generic Cialis without a doctor prescription – Cialis 20mg price

  25. BrettTIT表示:

    Cheapest Sildenafil online: buy viagra online – best price for viagra 100mg

  26. RogerFaf表示:

    http://fastpillsformen.com/# Cheap Viagra 100mg

  27. BrettTIT表示:

    buy viagra here: Fast Pills For Men – over the counter sildenafil

  28. MiguelBrola表示:

    The most exciting new trains coming in 2025
    промокод рив гош на повторный
    Amazing adventures, extraordinary landscapes and fabulous cuisine — the world’s greatest railway journeys are an unforgettable experience that can immerse you in the culture of a new country.

    Demand for luxury “land cruise” trains with five-star hotel-style accommodation is booming. 2025 will see several new trains take to the rails for the first time, offering new opportunities to explore Italy, France, Saudi Arabia and the United Kingdom.

    But the best railway journeys don’t have to be the most expensive. There’s an ever-evolving world of train trips out there. Here are some of the key developments in the coming year
    Two of Europe’s great capitals are now linked by their first direct high-speed train connection. Germany’s Deutsche Bahn introduced a daytime InterCity Express (ICE) service between Paris and Berlin on December 16 and is planning to add a second route between the two capitals in 2026.

    Taking advantage of its new fleet of 200 mph (322 kph) ICE3neo trains, the once-a-day service takes around eight hours in each direction, also serving Strasbourg, Karlsruhe and Frankfurt on its 546-mile (878-kilometer) journey.

    Fares start from around $60, and each train has capacity for 444 passengers, of which 111 can enjoy the additional comfort of leather seats and at-seat refreshments in first class.

    The new high-speed ICE service is the first direct daytime train between Paris and Berlin since the 1990s and complements the Nightjet sleeper service introduced in 2023.

    It may not be as fast as flying — some of the journey has to use lower speed “classic” lines to bridge gaps in the European high-speed network — but it is undoubtedly a more sustainable and more stylish way to travel across Europe.

  29. Barrybib表示:

    Cialis 20mg price in USA: buy cialis online – Generic Tadalafil 20mg price

發佈留言

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