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

  1. Практичные шторы для коттеджа
    шторы для коттеджа шторы для коттеджа .

  2. Elmerbuils表示:

    pin up az: pinup az – pin up az

  3. ZackaryGer表示:

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

  4. BrianStani表示:

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

  5. KennethKex表示:

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

  6. Richardfek表示:

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

  7. ZackaryGer表示:

    http://vavadavhod.tech/# vavada вход

  8. Vernonneato表示:

    Phoenix DEX is rewriting the rules of DeFi on Solana. As a core part of the Phoenix Exchange Solana ecosystem, it supports advanced tools like Phoenix Trade Bonk pairs, seamless Phoenix Trade Wallet access, and reliable Phoenix Trade Security. Curious about how it works? The Phoenix Trade Tutorial and Phoenix Trade Guide make it easy. Traders love the efficiency, especially with low Phoenix Trade Fees and the powerful Phoenix Trade Features. Phoenix where to begin? Visit https://phoenixtrade.me and trade smarter today!

  9. Elmerbuils表示:

    вавада казино: vavada casino – vavada

  10. Jasonthymn表示:

    Exploring token management? Liquifi is revolutionizing crypto with seamless, automated solutions. From Liquifi vesting to Liquifi Claim and Liquifi Receive, itтАЩs built for teams, DAOs, and protocols. With secure Liquifi token vesting and transparent Liquifi airdrop vesting, users gain total control. Curious about Liquifi reviews? Users love the experience and top-tier Liquifi security. Want to know Liquifi tutorial? ItтАЩs simpleтАФstart with the Liquifi app and scale with ease. Ready to go? Liquifi sign up now at https://liquifi.tech and streamline your vesting today!

  11. BrianStani表示:

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

  12. RobertApozy表示:

    смотреть онлайн бесплатно – деньги под расписку, смотреть фильмы онлайн

  13. KennethKex表示:

    pin up az: pin up az – pin up azerbaycan

  14. ZackaryGer表示:

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

  15. JosephSward表示:

    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://bccgame.org !

  16. KennethKex表示:

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

  17. Victorsox表示:

    Super Sushi Samurai is redefining gaming on the Blast Network! With real ownership through Super Sushi Samurai NFT, thrilling battles, and community-driven gameplay, it’s the perfect blend of fun and finance. Track the SSS token price, use your SSS token wisely, and dominate the Super Sushi Samurai land. From Super Sushi Samurai tutorial to Super Sushi Samurai crypto rewards, it’s all here. Ready to play? Visit https://sssgame.ink and become a sushi legend today!

  18. Ismaelendut表示:

    Say hello to SablierтАФthe leading platform for token streaming and vesting. Whether youтАЩre using Sablier token streaming for payroll, exploring Sablier vesting schedules, or claiming from a Sablier Airdrop Claim, itтАЩs all powered by Sablier Labs and the advanced Sablier API. Wondering how secure it is? The verified Sablier audit speaks for itself. Use your Sablier bonus code and start streaming at https://sablier.cc today!

  19. Ismaelendut表示:

    Sablier is built for builders, teams, and DAOs. With powerful Sablier token vesting, Sablier mirror integration, and Sablier crypto tools, itтАЩs the go-to for real-time finance. Backed by the trusted Sablier protocol and Sablier Labs, you can stream confidently on Sablier Ethereum. Need to claim? Use Sablier Claim or explore the Sablier app to manage it all. Visit https://sablier.cc and experience financial automation like never before!

  20. DwayneRoP表示:

    Say hello to Sky Money—the future of crypto finance. Backed by Spark Protocol Sky and MakerDAO Sky, users benefit from stable tools like USDS Sky, USDS ETH, and sUSDS Sky. Whether you’re earning Sky Token Rewards or exploring SKY token potential, the platform offers everything you need. Learn more about sky crypto, how Sky Protocol works, and start earning today at https://skymoney.net !

  21. Elmerbuils表示:

    pin up azerbaycan: pin up casino – pin up azerbaycan

  22. ZackaryGer表示:

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

  23. TerryDek表示:

    The voice of ‘White Lotus’ star Walton Goggins is the lullaby we didn’t know we needed
    jumper exchange
    While his “White Lotus” character Rick has been the source of some stress this season, Walton Goggins is here to soothe us into a state of dreamy sleep to make up for it.

    The actor has partnered with relaxation and meditation app Calm for one of their famed Sleep Stories, lending his smoky voice to a fable titled “The Yard Sale.”

    Goggins announced the Sleep Story on his verified Instagram on Tuesday, writing, “A friend once said to me the first question you ask someone shouldn’t be, ‘How are you?’ but rather, ‘How did you sleep last night?’ I agree.”

    The post included an excerpt from the story, in which Goggins is heard languidly instructing listeners to relax their bodies and get into bed. “You could even climb into a hammock,” he added. “I wouldn’t do that because I’ve never gracefully got in or out of one.”

    In the caption, the actor also wrote that he “wanted to create a Sleep Story that feels dreamlike, helping people slow their minds down by wandering through a yard sale (which happens to be one of my favorite things to do), uncovering hidden treasures.”

    “It’s the Walton Goggins version of counting sheep. I hope you enjoy,” he added.

    Other celebrities who have read bedtime stories in the hopes of putting audiences to sleep include Dolly Parton and the late Jimmy Stewart, whose voice was featured in a Calm Christmas Sleep Story in 2023 thanks to generative AI technology.

    Goggins currently stars on “The White Lotus,” where his character is often the most stressed out and tortured of the ensemble, at one point setting a slew of snakes free.

  24. Elmerbuils表示:

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

  25. Brianbleft表示:

    Say hello to ThorSwap—your ultimate multi-chain trading hub. From Thor Crypto Change to THORYield and ThorSwap Staking, every feature is designed to maximize your DeFi experience. The ThorSwap THOR Token powers governance and rewards, with real-time ThorSwap Token Price updates and full ThorSwap NFT Support. Need help? ThorSwap Documentation has you covered, and the ThorSwap Referral Program brings extra rewards. Start earning today at https://thorswap.cc !

  26. JamesMaf表示:

    Instadapp is built for the future of finance! With smart Instadapp Fluid automation, deep integration with Instadapp MakerDAO, and full Instadapp Security/Audit transparency, it’s trusted by thousands. Whether you’re exploring Instadapp Pro, managing Instadapp Flashloan tools, or claiming your Instadapp Airdrop, everything is simple and secure. Want to understand Instadapp Governance or the INST Token? It’s all in the Instadapp overview. Ready to start? Visit http://instaoapp.com and join the next generation of DeFi now!

  27. Доверьтесь профессионалам: автоматика Somfy
    Автоматика Somfy Автоматика Somfy . Prokarniz

  28. BrianStani表示:

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

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

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