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

14,907 Responses

  1. Brianlit表示:

    rybelsus semaglutide tablets semaglutide tablets price semaglutide tablets for weight loss

  2. phimguru.com表示:

    Asking questions aare really pleaant thing if
    you are not understandingg anything entirely,
    bbut thios article ppresents fastidious understanding yet.

  3. AlbertNer表示:

    http://predpharm.com/# prednisone 2.5 mg cost
    prednisone 5mg price

  4. Nasosy_ndPl表示:

    купить насос для воды https://nasosy-msk.ru/ .

  5. DanielZek表示:

    https://semapharm24.shop/# generic rybelsus tabs
    Kamagra tablets

  6. Waltererync表示:

    Kama Pharm: Kama Pharm – Kama Pharm

  7. LarryLog表示:

    Kama Pharm: Kama Pharm – Kama Pharm

  8. AlbertNer表示:

    https://cytpharm.shop/# buy misoprostol over the counter
    prednisone 5 mg tablet cost

  9. DanielZek表示:

    http://cytpharm.com/# cytotec abortion pill
    cheap kamagra

  10. Nasosy_urPl表示:

    насос глубинный насос глубинный .

  11. Waltererync表示:

    cheap priligy: dap pharm – dapoxetine price

  12. Antonioamorb表示:

    Why expanding the College Football Playoff worked – and what still needs to be fixed
    красивый анальный секс
    Now that it’s all over and the Ohio State Buckeyes are the college football national champions, it can be definitively said: expanding the College Football Playoff worked.

    The grand experiment to allow more teams to play for the national championship wasn’t perfect, but it ended up where it was supposed to: a worthy national champion with exciting, close games in the later rounds when the best teams faced one another. It gave us awesome scenes on campuses around the nation, created new legends and showed how a sport so steeped in tradition can evolve when faced with new demands from its fans and business partners.

    Here are four reasons why the new version of the College Football Playoff worked – and the areas that can still be fixed.

    The committee picked the right teams, even if some games were blowouts
    Before the games kicked off in December, much of the focus was put on the inclusion of Southern Methodist University (SMU) and Indiana University – two teams that won a bunch of games but didn’t have the brand recognition of schools like Alabama, South Carolina and Ole Miss.

    Here’s what else those teams had that SMU and Indiana didn’t: three losses.

    The Hoosiers lost only once in the regular season – to eventual national champion Ohio State. The Mustangs had lost twice, once to Brigham Young University and again in the ACC championship game to Clemson.

    In the first year of the expanded, 12-team playoff, could the committee really leave out a major conference team with 11 wins and punish another one for playing for a conference championship while other teams sat at home? Warde Manuel, the University of Michigan athletic director who served as chair of the committee, said they could not.

  13. AlbertNer表示:

    https://cytpharm.shop/# buy cytotec online
    prednisone 1 mg for sale

  14. LarryLog表示:

    prednisone 50: Pred Pharm – Pred Pharm

  15. This website really has all the info I wanted concerning this subject and didn’t know who to ask.

  16. DanielZek表示:

    https://semapharm24.com/# semaglutide tablets
    buy kamagra online usa

  17. kolyaska_qdsn表示:

    Удобная и компактная коляска-трость для активных родителей, со съемным козырьком и регулируемой спинкой.
    Новейшая коляска-трость с механизмом складывания одной рукой, и удобным выдвижным козырьком.
    Модная коляска-трость для маленького модника, которая станет вашим незаменимым помощником.
    Качественная коляска-трость с удобной ручкой, и мягкими ремнями безопасности.
    elodie details трость https://kolyaski-trosti-progulochnye.ru/ .

  18. Waltererync表示:

    buy misoprostol over the counter: cytotec online – Cyt Pharm

  19. kolyaska_rrsn表示:

    Выбор современных родителей – коляска-трость, с прочными колесами и удобной ручкой.
    Стильная и практичная коляска-трость для вашего малыша, которая поможет вам в повседневных прогулках.
    Купите легкую и компактную коляску-трость по доступной цене, которая станет вашим незаменимым помощником.
    Качественная коляска-трость с удобной ручкой, и мягкими ремнями безопасности.
    babyhit коляска трость https://kolyaski-trosti-progulochnye.ru/ .

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

  21. kolyaska_misn表示:

    Выбор современных родителей – коляска-трость, со съемным козырьком и регулируемой спинкой.
    Новейшая коляска-трость с механизмом складывания одной рукой, с многофункциональной корзиной для покупок.
    Купите легкую и компактную коляску-трость по доступной цене, которая станет вашим незаменимым помощником.
    Элегантная коляска-трость для путешествий и прогулок, с прочными колесами и удобной спинкой.
    коляска трость купить коляска трость купить .

  22. kolyaska_rasn表示:

    Выбор современных родителей – коляска-трость, с прочными колесами и удобной ручкой.
    Эргономичная коляска-трость с эффектным дизайном, которая поможет вам в повседневных прогулках.
    Модная коляска-трость для маленького модника, которая станет вашим незаменимым помощником.
    Элегантная коляска-трость для путешествий и прогулок, с прочными колесами и удобной спинкой.
    chicco трость chicco трость .

  23. LarryLog表示:

    Pred Pharm: how to purchase prednisone online – PredPharm

  24. AlbertNer表示:

    https://kamapharm.shop/# п»їkamagra
    20 mg prednisone

  25. Begin By Meeting The Steve Jobs Of The Affordable Couches For Sale Industry Sofa Chairs For Sale

  26. AlbertNer表示:

    http://semapharm24.com/# cheap semaglutide pills
    prednisone 10mg

  27. Briantuh表示:

    Фильмы новинки, которые уже вышли или выйдут совсем скоро онлайн бесплатно и в хорошем качестве. Будьте первыми зрителями наиболее выдающихся кинокартин

    https://filmy-2025.cc/

  28. kolyaska_owsn表示:

    Купите современную коляску-трость для вашего малыша, со съемным козырьком и регулируемой спинкой.
    Эргономичная коляска-трость с эффектным дизайном, с многофункциональной корзиной для покупок.
    Модная коляска-трость для маленького модника, с удобной ручкой и амортизаторами.
    Компактная коляска-трость для активных мам и пап, и мягкими ремнями безопасности.
    babyton zoo купить babyton zoo купить .

  29. kolyaska_pwsn表示:

    Купите современную коляску-трость для вашего малыша, со съемным козырьком и регулируемой спинкой.
    Стильная и практичная коляска-трость для вашего малыша, и удобным выдвижным козырьком.
    Купите легкую и компактную коляску-трость по доступной цене, с вместительной корзиной и мягкими подушками.
    Компактная коляска-трость для активных мам и пап, которая облегчит вам заботу о ребенке.
    babyhit трость https://kolyaski-trosti-progulochnye.ru/ .

  30. Waltererync表示:

    dap pharm: dap pharm – buy dapoxetine online

發佈回覆給「kolyaska_misn」的留言 取消回覆

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