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,934 Responses

  1. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт холодильников siemens, можете посмотреть на сайте: ремонт холодильников siemens
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  2. Lannyhat表示:

    La variedad de juegos es impresionante.: jugabet.xyz – jugabet chile

  3. JosephCyday表示:

    jugabet jugabet Los casinos organizan eventos especiales regularmente.

  4. Patrickspogs表示:

    Promotions are advertised through social media channels.: phmacao com login – phmacao.life

  5. Lannyhat表示:

    The poker community is very active here.: taya777.icu – taya777 login

  6. Williamgox表示:

    Game rules can vary between casinos. http://phmacao.life/# The Philippines offers a rich gaming culture.

  7. Davidzem表示:

    http://phmacao.life/# The casino scene is constantly evolving.
    Slot machines feature various exciting themes.

  8. Davidzem表示:

    https://taya777.icu/# Casinos often host special holiday promotions.
    Manila is home to many large casinos.

  9. Lannyhat表示:

    Casino visits are a popular tourist attraction.: phmacao club – phmacao.life

  10. Patrickspogs表示:

    п»їCasinos in the Philippines are highly popular.: phmacao club – phmacao.life

  11. The 10 Most Terrifying Things About Gas Safe Register Engineer
    gas Safe register engineer

  12. Lannyhat表示:

    Las ganancias son una gran motivaciГіn.: winchile – win chile

  13. Patrickspogs表示:

    Live dealer games enhance the casino experience.: taya777.icu – taya777 login

  14. Davidzem表示:

    http://phtaya.tech/# The casino scene is constantly evolving.
    The thrill of winning keeps players engaged.

  15. Davidzem表示:

    https://winchile.pro/# Los jackpots progresivos atraen a los jugadores.
    Players often share tips and strategies.

  16. JosephCyday表示:

    jugabet casino jugabet casino La mГєsica acompaГ±a la experiencia de juego.

  17. MfopazMep表示:

    Понадобилось 30 000 рублей на лечение родственника, но в банке отказали. В Facebook наткнулся на обсуждение, где советовали Новые займы 2025 – что предлагают малоизвестные МФО . Оказалось, там реально можно найти компании, которые дают деньги даже с плохой кредитной историей. Заполнил анкету – одобрили за 5 минут, а ещё через 10 деньги были у меня.

  18. Williamgox表示:

    Loyalty programs reward regular customers generously. https://phmacao.life/# The casino industry supports local economies significantly.

  19. What Are The Reasons You Should Be Focusing On Making Improvements In Pram
    2 In 1 2 in 1 pushchair And Car Seat

  20. Lannyhat表示:

    Es comГєn ver jugadores sociales en mesas.: jugabet.xyz – jugabet casino

  21. JosephCyday表示:

    taya777 register login taya777.icu The Philippines offers a rich gaming culture.

  22. Williamgox表示:

    The poker community is very active here. https://taya365.art/# Players enjoy a variety of table games.

  23. Patrickspogs表示:

    Slot machines attract players with big jackpots.: taya365 com login – taya365

  24. Williambob表示:

    They’ve sailed across Southeast Asia for centuries. Now, these sea nomads are being forced to live on land
    скупка приставок
    Bilkuin Jimi Salih doesn’t remember how old he was when he learned to dive, only, that all the men in his family can do it.

    It might have been his grandfather who taught him, or his father, or even an uncle or cousin. He recalls swimming dozens of feet underwater among the reefs, collecting spider conches, abalone and sea cucumbers to sell at the local fish market.

    “One of our specialties is that, because we live on the sea and we’re always in the sea, we can dive in the water for a long time,” says Salih, via a translator. “We learn by observing, and from there, we develop our own technique.”

    To most people, Salih’s free diving skills are highly unusual; but not to his community. Salih is Bajau Laut, an indigenous seafaring group in Southeast Asia that has lived a semi-nomadic lifestyle on the ocean for centuries. Living on boats and fishing for income and sustenance, the Bajau Laut aren’t just reliant on the sea: they’re biologically adapted to it, with larger spleens that give them the ability to hold their breath for far longer than the average person.

    “We’re very comfortable in the water,” says Salih. The 20-year-old was born on board a lepa, a type of houseboat, on the shore of Omadal Island, off the coast of Semporna in Malaysian Borneo.

  25. Patrickspogs表示:

    Live music events often accompany gaming nights.: phtaya login – phtaya casino

  26. Lannyhat表示:

    Las tragamonedas ofrecen grandes premios.: win chile – winchile.pro

發佈留言

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