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

  1. You must participate in a contest for one of the best blogs on the web. I’ll recommend this web site!

  2. Good aftie” i am a blogger too” and i can see that you are a nice blogger too. 

  3. I am usually to blogging i actually appreciate your posts. The content has really peaks my interest. I will bookmark your website and keep checking for brand new data.

  4. hvac near me表示:

    Hi there, I’m an advanced university student and also I’m finding out considerably about writing as a result of writing about blogs and forums. I adore look in composing. It’s simple to implement though with very good information. A person’s language causes it to become pleasurable to learn to read and even have an understanding of. That’s an immense portion of producing. An individual’s admirers have to be rrn a position to realise what you’re indicating as well as posting really need to be interesting. You’ll want to challenge your readers, to make sure they will come back for much more. You are doing a great job wonderful a lot of these elements. Appreciate it!

  5. WilliamTic表示:

    В нашем мире, где аттестат становится началом удачной карьеры в любом направлении, многие пытаются найти максимально быстрый путь получения образования. Наличие официального документа сложно переоценить. Ведь диплом открывает двери перед любым человеком, желающим вступить в профессиональное сообщество или учиться в высшем учебном заведении.
    В данном контексте наша компания предлагает максимально быстро получить этот необходимый документ. Вы можете заказать аттестат нового или старого образца, что является отличным решением для человека, который не смог закончить обучение или утратил документ. Любой аттестат изготавливается аккуратно, с максимальным вниманием ко всем деталям. В результате вы получите 100% оригинальный документ.
    Плюсы подобного подхода состоят не только в том, что можно оперативно получить аттестат. Весь процесс организовывается удобно, с профессиональной поддержкой. Начиная от выбора подходящего образца документа до консультаций по заполнению личной информации и доставки в любой регион страны — все под абсолютным контролем наших мастеров.
    Для всех, кто ищет максимально быстрый способ получить требуемый документ, наша компания предлагает выгодное решение. Купить аттестат – значит избежать долгого обучения и сразу переходить к личным целям, будь то поступление в ВУЗ или начало профессиональной карьеры.

    https://maps.google.tl/url?q=http://aurus-diploms.com

  6. Citroen keys表示:

    10 Tell-Tale Signs You Must See To Get A New Citroen Key Fob Citroen keys

  7. The 10 Most Infuriating Motorcycle Accident Compensation Fails Of All Time Could
    Have Been Avoided Motorcycle Accident Law Firms

  8. I have realized some considerations through your blog post. One other stuff I would like to talk about is that there are numerous games on the market designed specifically for toddler age young children. They include pattern acknowledgement, colors, dogs, and styles. These generally focus on familiarization instead of memorization. This keeps little ones occupied without having a sensation like they are studying. Thanks

  9. Definitely believe that which you said. Your favourite reason seemed to be on the internet the simplest factor to consider of. I say to you, I definitely get irked at the same time as other people think about issues that they just don’t recognise about. You managed to hit the nail upon the top well defined out the entire thing without having side effect , other folks could take a signal. Will probably be again to get more. Thank you!

  10. I’d have to check with you here. Which isn’t something I usually do! I get pleasure from reading a put up that can make people think. Additionally, thanks for allowing me to remark!

  11. Not long noticed concerning your web site and are still already reading along. I assumed i’ll leave my initial comment. i do not verify what saying except that I’ve enjoyed reading. Nice blog. ill be bookmarking keep visiting this web site really usually.

  12. Glass Repairs表示:

    Here’s A Few Facts About Upvc Windows Crawley Glass Repairs

  13. Nice post. I study something tougher on totally different blogs everyday. It is going to always be stimulating to learn content from different writers and observe a little bit something from their store. I’d choose to make use of some with the content on my blog whether you don’t mind. Natually I’ll provide you with a link in your web blog. Thanks for sharing.

  14. I simply needed to make a quick comment as a way to express gratitude for you for anyone wonderful pointers you happen to be posting here. My time consuming internet investigation has right at the end of waking time been rewarded with good quality ways of present to my guests. I would state that many people readers are actually endowed to take place in an incredible network with the greatest marvellous those with useful hints. I am quite privileged to own used your webpages and look toward really more fabulous minutes reading here. Many thanks for a number of things.

  15. you can get some free catalogs over the internet easily if you just search on google**

  16. Your blog is spectacular. A lot of the things on your own page are usually my consent concerning. we appreciate you discussing.

  17. Hiya! I simply wish to give an enormous thumbs up for the great data you will have right here on this post. I can be coming back to your blog for extra soon.

  18. I used to be able to find good information from your blog articles.

  19. Lock表示:

    Ten Window Repair Near Me-Related Stumbling Blocks
    You Should Not Share On Twitter Lock

  20. fitters表示:

    Your Worst Nightmare About Double Glazing Supplies Near Me Come To Life fitters

  21. attorneys表示:

    Its History Of Auto Accident Legal attorneys

  22. 20 Quotes That Will Help You Understand Upvc Front Doors Hinges For upvc doors

  23. Ten Best Online Shopping Sites Clothes-Related Stumbling Blocks You Should
    Never Share On Twitter Automotive Welding Cable

  24. The 10 Most Scariest Things About Window Repairs Near Me window
    repairs near me (https://minecraftcommand.science/profile/doubtvalue07)

  25. game表示:

    Ten Things You Learned At Preschool That’ll Help You Understand CS GO Gambling Sites game

  26. Ok oui et pas vraiment. Assurément parce que il se peut qu’on rencontre certaines sources qui probablement citent de semblables cote. Non car il ne suffit pas de copier ce qu’on peut lire avec plusieurs site web autres avant de le transposer tant clairement

  27. Lewisslund表示:

    Hi there! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Thank you!
    http://arusak-attestats24.com

    Today, I went to the beachfront with my children. 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 put 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 entirely off topic but I had to tell someone!

  28. ac tune up表示:

    you have a wonderful blog here! would you like to have invite posts on my own blog?

  29. Nmixdq表示:

    dimenhydrinate 50 mg sale – prasugrel 10 mg usa actonel 35mg pill

  30. Excellent stuff. I can’t describe how much your site has helped me within my academic research on the subject. I’m now likely to get top marks without a doubt. Thanks a thousand. I owe you one.

發佈留言

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