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

7,842 Responses

  1. DichaelDax表示:

    Right here is the right site for anybody who would like to understand this topic. You understand a whole lot its almost tough to argue with you (not that I actually would want to…HaHa). You definitely put a fresh spin on a subject that has been discussed for decades. Excellent stuff, just excellent!
    arusak-attestats24.com

    Hello there I am so delighted I found your webpage, I really found you by error, while I was searching on Askjeeve for something else, Regardless I am here now and would just like to say thanks a lot for a remarkable post and a all round entertaining blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read much more, Please do keep up the fantastic b.

  2. OLaneevige表示:

    Wow, fantastic weblog structure! How lengthy have you ever been blogging for? you make running a blog glance easy. The entire look of your web site is great, as neatly as the content!

    woke.party/blogs/104615/%D0%94%D0%B8%D0%BF%D0%BB%D0%BE%D0%BC-%D0%BA%D0%BE%D0%BB%D0%BB%D0%B5%D0%B4%D0%B6%D0%B0-%D0%B2-2024-%D0%B3%D0%BE%D0%B4%D1%83-%D0%9E%D1%81%D0%BE%D0%B1%D0%B5%D0%BD%D0%BD%D0В 
    stroimnsk.ru/wooden/proekt-derevyannogo-doma-iz-profilirovannogo-brusa-skazka-100/В 
    stroyzapadnoe.ru/%D0%B3%D0%BE%D1%82%D0%BE%D0%B2%D1%8B%D0%B5-%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D1%8B/nggallery/thumbnailsВ 
    rem.4nmv.ru/forum/profile.php?action=show&member=5100В 
    uapa.com.hk/forum/home.php?mod=space&uid=292023&do=profileВ 

  3. 주부대출表示:

    What Not To Say In A Personal Unsecured Loan Application 주부대출

  4. Ten Things You Learned In Kindergarden They’ll Help You Understand Upvc Windows And Doors
    Near Me replacing upvc door lock

  5. Vimeo表示:

    10 Things We All Love About Shopping Online Vimeo

  6. The 10 Scariest Things About Online Casino Slots Online Casino Slots (https://Zzb.Bz/64XDl)

  7. There were countless one liners that made me chuckle or laugh.

  8. Thank you, I’ve recently been searching for information about this subject for ages and yours is the best I have discovered till now. But, what about the bottom line? Are you sure about the source?

  9. This is a correct blog for anybody who really wants to be made aware of this topic. You understand so much its practically challenging to argue along (not too I actually would want…HaHa). You certainly put the latest spin with a topic thats been discussed for decades. Great stuff, just wonderful!

  10. Vudarn表示:

    order forxiga 10 mg pills – acarbose 25mg over the counter how to get precose without a prescription

  11. Who Is Responsible For A Window Repairs Bedford Budget? 12 Top Notch Ways To
    Spend Your Money bedford doors and windows

  12. Renault Clio Replacement Key Tools To Ease Your Everyday Lifethe Only Renault Clio
    Replacement Key Trick Every Individual Should Know renault clio replacement key

  13. It is really a great and helpful piece of info. I am glad that you just shared this helpful information with us. Please stay us informed like this. Thanks for sharing.

  14. Why Truck Accident Compensation Claims Isn’t A Topic That People Are Interested In Truck Accident Compensation Claims Truck Accident Attorneys

  15. Spot lets start on this write-up, I really think this amazing site needs much more consideration. I’ll more likely once more to see a great deal more, thank you that info.

  16. One Of The Biggest Mistakes That People Make With Replacement Windows
    Milton Keynes french doors Milton keynes

  17. i like wireless internet because you can surf anywhere and you can avoid those ethernet cables,

  18. 소액대출表示:

    5 Techniques For Travel Without Having To Break The Bank 소액대출

  19. Tommyphito表示:

    Keep on writing, great job!
    http://veniaminv.flybb.ru/viewtopic.php?f=1&t=2611

  20. Tommyphito表示:

    Today, I went to the beach front with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!
    http://forumkrasnoperekopsk.rx22.ru/viewtopic.php?f=14&t=1157

  21. Oh my goodness! a fantastic post dude. Many thanks However We are experiencing problem with ur rss . Don’t know why Can not sign up to it. Could there be anybody finding identical rss difficulty? Anyone who knows kindly respond. Thnkx

  22. Tommyphito表示:

    Кофе в капсулах системы Nespresso. Мы предлагаем широкий ассортимент кофе в капсулах, более 200 вкусов. Доставка СДЭК 1-3 дня в любой город Беларуси или России. Оплата при получении.
    капсулы nespresso

  23. kitchen designs that makes use of space efficiently would be the best thing to go with’

  24. berlin… […]u Not every blog has got the facts right but this one seems to have managed t ld[…]…

  25. Ses表示:

    A recovering gambling addict, she had used a national self-exclusion scheme to bar herself from online casinos. There is no such scheme for computer gaming. After signing up for one of the best paying online casinos, it’s time to pick which games to play. To make this easier, we’ve researched which online slots, table, and specialty games have the highest RTP and provide the best casino payouts. Stick with these titles to enjoy better value and higher payouts online. Online casino slot games are said to use the same kinds of random number generator programs as land-based casinos. They serve up your results via animation sent to your computer via the Internet. This website is for the use of adults 19 years of age or older in the Province of Ontario. Gambling can be addictive. Please play responsibly. Connexontario.ca 1-866-531-2600
    https://www.believingwomen.org.uk/300-money-surplus-gambling-%EF%B8%8F-have-got-3-hundred-deposit-rewards-when-you-look-at-the-ontario/
    Bally Slot Machine Chasing elusive bonus games used to be a challenge but not anymore. Taking the industry by storm are games that offer you a shortcut for a certain moderate or at times mind-blowing price. Here’s an amazing collection of feature buy demo slots to introduce you to this exciting category. Several regulatory bodies control casinos to ensure players feel safe and legally play slot machines. Casinos undergo many checks according to gamblers’ different requirements and casino operating country. The primary casino regulators are the following: FREE TICKET IN – TICKET OUT & FREE PLAY OPTION (TITO) WITH EACH MACHINE PURCHASED.  INCLUDES ALL ARISTOCRAT, BALLY, IGT AND WMS MACHINES. UP TO A $275 VALUE PER MACHINE. ADD MACHINE TO CART FOR THIS SPECIAL OFFER! (NEW ORDERS THROUGH MAY 31)

  26. This Is The History Of How To Ship To Ireland From Uk In 10 Milestones Marla Red Rug 5’3″X7’3″

  27. free Slots表示:

    The 10 Scariest Things About Free Slots free Slots

  28. Tommyphito表示:

    Прокат автомобиля в Минске – на час, день или более длительный период – в наше время не роскошь, а необходимость.В большом городе человек без машины, как без рук – ничего не успеть!
    аренда авто на сутки

  29. Upvc Door Repairs Near Me Tools To Improve Your Daily Life Upvc Door Repairs Near Me Trick That Everybody
    Should Be Able To Upvc door repairs near Me

發佈留言

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