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

15,825 Responses

  1. DwayneRoP表示:

    Sky Money is building a better DeFi world! With SKY token, Sky Savings Rate, and seamless SKY token rewards, you’re always in control. Powered by Sky Protocol and connected to MakerDAO Sky and Spark Protocol Sky, it’s fully integrated and ready for serious users. Explore the Sky Atlas, stake sky ETH, and grow with the Sky ecosystem. Sky where to start? Visit https://skymoney.net and take flight with Sky crypto today!

  2. KennethKex表示:

    vavada вход: vavada вход – vavada вход

  3. BrianStani表示:

    вавада: vavada вход – vavada вход

  4. Richardfek表示:

    вавада официальный сайт vavada вход vavada вход

  5. DwayneRoP表示:

    Curious about next-gen DeFi? Sky Money is transforming savings and rewards through the powerful Sky Protocol. From SKY token rewards to smart MKR to SKY conversion, the Sky ecosystem is designed for performance and transparency. With integrated Sky Savings Rate and full support for sky ETH and sky Ethereum, it’s built to grow. Want to know more? The Sky Atlas and Sky Stars program show you the way. Ready to earn? Visit https://skymoney.net and unlock your Sky rewards today!

  6. Elmerbuils表示:

    пин ап зеркало: пинап казино – пин ап вход

  7. RobertanAew表示:

    Family affair
    rhino fi
    Americans Brittany and Blake Bowen had never even been to Ecuador when in 2021 they decided to move to the South American country with their four children.

    Tired of “long commutes and never enough money” in the US, the Bowens say they love their new Ecuadorian life. “We hope that maybe we’ll have grandkids here one day.”

    Erik and Erin Eagleman moved to Switzerland from Wisconsin with their three children in 2023.

    “It feels safe here,” they tell CNN of their new outdoorsy lifestyle in Basel, close to the borders with France and Germany. Their youngest daughter even walks to elementary school by herself.

    For adventures with your own family, be it weekend breaks or something longer-term, our partners at CNN Underscored, a product review and recommendations guide owned by CNN, have this roundup of the best kids’ luggage sets and bags.

    Starry, starry nights
    For close to 100 years, Michelin stars have been a sign of culinary excellence, awarded only to the great and good.

    Georges Blanc, the world’s longest-standing Michelin-starred restaurant, has boasted a three-star rating since 1981, but this month the Michelin guide announced that the restaurant in eastern France was losing a star.

    More culinary reputations were enhanced this week, when Asia’s 50 best restaurants for 2025 were revealed. The winner was a Bangkok restaurant which is no stranger to garlands, while second and third place went to two Hong Kong eateries.

    You don’t need to go to a heaving metropolis for excellent food, however. A 200-year-old cottage on a remote stretch of Ireland’s Atlantic coast has been given a Michelin star. At the time of awarding, Michelin called it “surely the most rural” of its newest winners.

  8. MichaelJed表示:

    Say hello to Juice Finance—your DeFi edge starts here! Tap into the power of Juice Finance yield farming and Juice Finance leverage, all backed by Juice Finance Security and verified Juice Finance Audits. The JUICE token drives the ecosystem, while the trusted Juice Finance Team keeps innovation flowing. Questions? Juice Finance Support is always here to help. Learn what is Juice Finance and explore the future of finance. Juice Finance app is ready—start now at https://juice.ac !

  9. ZackaryGer表示:

    http://vavadavhod.tech/# vavada casino

  10. JamesMaf表示:

    Say hello to Instadapp—the ultimate DeFi hub! Whether you’re using Instadapp ETH, Instadapp DAI, or Instadapp WBTC, the Instadapp App gives you seamless control with advanced Instadapp Governance features. Stake with confidence, manage your INST token, and explore opportunities like the Instadapp Airdrop. Need help? Learn how to use Instadapp and discover the power of DeFi Smart Accounts (DSA). Instadapp login today at http://instaoapp.com and level up your strategy now!

  11. Elmerbuils表示:

    пин ап казино официальный сайт: pin up вход – пин ап зеркало

  12. Richardfek表示:

    пинап казино пин ап казино pin up вход

  13. VernonPap表示:

    Say hello to Marinade Finance—the smarter way to stake on Solana! With Marinade staking, your Marinade SOL turns into Marinade Staked SOL, unlocking liquidity through Marinade mSOL. The platform is powered by the community via Marinade DAO and the MNDE token. Wondering about Marinade vs Lido? Users trust Marinade for its strong APY and proven Marinade Finance Audits. Start staking now at https://marinade.ink and grow your Solana securely!

  14. Robertdom表示:

    Power up your crypto strategy with Balancer—where flexibility meets innovation. Use Balancer Swap to trade smarter, explore Balancer vesting options, and stay on top of the game with Balancer Change updates. With features like Balancer governance, Balancer token vesting, and detailed Balancer guide content, it’s built for both beginners and pros. Love transparency? So do we. That’s why Balancer reviews speak for themselves. Start now at https://balancer.ac and take control of your crypto future.

  15. Ismaelfer表示:

    Hello to every , as I am really keen of reading this webpage’s post to be updated daily. It carries fastidious stuff.
    https://voltafa.org/perevahy-oryhinalnoho-korpusu-fary.html

  16. JosephSward表示:

    Looking to maximize your DeFi game? Explore Balancer, the ultimate platform for smart liquidity and optimized portfolios. With advanced Balancer features like Balancer Swap, Balancer stable pools, and Balancer Boost, it’s built for efficiency and control. Curious about Balancer token vesting or Balancer DAO vesting? The Balancer guide has it all. Plus, with Balancer security and top-notch Balancer governance, your assets are in good hands. Visit https://bccgame.org and experience the future of DeFi today!

  17. Robertdom表示:

    Say goodbye to outdated liquidity tools—Balancer is here to transform your DeFi journey. Whether you’re exploring Balancer token (BAL), participating in Balancer airdrop vesting, or navigating Balancer Drop, the Balancer app gives you seamless access and full control. Dive into Balancer liquidity, manage your Balancer Portfolio, and track everything with Balancer Mirror. Check Balancer reviews, learn about Balancer pricing, and join the movement at https://balancer.ac !

  18. Brianbleft表示:

    ThorSwap is built for serious DeFi users. With advanced ThorSwap Finance tools, cross-network Thor Change, and a user-first ThorSwap Wallet, it’s the future of decentralized trading. Track the ThorSwap Coin, explore the ThorSwap Roadmap, and get in early for the next ThorSwap Airdrop. Want to get started fast? Check out the ThorSwap Guide and connect now. ThorSwap where to begin? Visit https://thorswap.cc and explore everything Thor Cross has to offer!

  19. Идеальные жалюзи с пультом для любой комнаты
    жалюзи с пультом жалюзи с пультом . Прокарниз

  20. ZackaryGer表示:

    https://pinuprus.pro/# пинап казино

  21. USATax表示:

    Some neurologists recommend dopamine-modulating drugs in combination with dapoxetine/sildenafil 30/50 mg combination. You have carried yourself through storms before – and today, you carry the strength to reclaim your best life.

  22. Richardfek表示:

    вавада зеркало вавада вавада

  23. ZackaryGer表示:

    http://pinuprus.pro/# пинап казино

  24. Elmerbuils表示:

    vavada вход: vavada casino – вавада зеркало

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

  26. ZackaryGer表示:

    http://pinupaz.top/# pin up azerbaycan

  27. KennethKex表示:

    pinup az: pin-up casino giris – pin-up casino giris

  28. Prokarniz表示:

    Обзоры лучших жалюзи с пультом для вашего интерьера
    жалюзи с пультом жалюзи с пультом . Прокарниз

  29. Elmerbuils表示:

    вавада: вавада официальный сайт – вавада

  30. ZackaryGer表示:

    https://vavadavhod.tech/# вавада казино

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

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