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

  1. When I originally commented I seem to have clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I get four emails with the same comment. Is there a means you are able to remove me from that service? Appreciate it.

  2. slot symbols表示:

    5 Tools That Everyone Working Involved In Slot
    Machines Industry Should Be Utilizing slot symbols

  3. Cheapest Online Grocery Shopping Uk It’s
    Not As Hard As You Think Ice Fishing Shelter

  4. hvac near me表示:

    Regards for this howling post, I am glad I found this internet site on yahoo.

  5. cheapest表示:

    What’s The Ugly The Truth About Search Engine Optimisation Agency cheapest

  6. I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thx again!

  7. You should be a part of a tournament first of the greatest blogs on the internet. I’ll suggest this website!

  8. 10 Things That Your Family Taught You About France Online Shopping Sites Clothes france online shopping Sites clothes

  9. […]the time to read or visit the content or sites we have linked to below the[…]…

  10. In this awesome design of things you’ll secure a B+ for hard work. Exactly where you actually misplaced me ended up being on your specifics. You know, it is said, details make or break the argument.. And it couldn’t be more true at this point. Having said that, let me tell you precisely what did give good results. Your authoring is actually quite convincing and that is most likely why I am making the effort in order to opine. I do not make it a regular habit of doing that. Next, despite the fact that I can see the jumps in reasoning you come up with, I am not necessarily certain of just how you appear to unite your points which in turn make your conclusion. For the moment I will, no doubt subscribe to your issue but wish in the near future you connect your dots better.

  11. elton john can be only be the best singer and composer that i know. i like the song Candle In The Wind;

  12. im surpirsed this post hasnt got more attention, get some backlinks friend and move it to the top of Google.

  13. Oh my goodness! a tremendous article dude. Thanks Nonetheless I’m experiencing challenge with ur rss . Don know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anyone who knows kindly respond. Thnkx

  14. ac service表示:

    wonderful put up, very informative. I’m wondering why the opposite experts of this sector do not realize this. You should proceed your writing. I am sure, you’ve a huge readers’ base already!

  15. in business, proper financial planning is very essential and it can make or break a business”

  16. Five Killer Quora Answers To Fela Claims
    Railroad Employees Fela Claims railroad employees

  17. The the next time I just read a blog, I hope so it doesnt disappoint me around this place. After all, It was my option to read, but When i thought youd have something fascinating to mention. All I hear is often a few whining about something that you could fix should you werent too busy looking for attention.

  18. Bujkpm表示:

    monograph drug – order cilostazol 100 mg sale order cilostazol 100mg

  19. I have to express some thanks to you for bailing me out of this challenge. After scouting throughout the internet and coming across concepts which were not powerful, I was thinking my entire life was done. Living devoid of the answers to the issues you have sorted out as a result of your article content is a crucial case, as well as the kind that would have badly damaged my entire career if I hadn’t encountered your blog. Your primary knowledge and kindness in controlling almost everything was precious. I am not sure what I would have done if I had not encountered such a subject like this. I can at this point look forward to my future. Thanks for your time so much for your expert and result oriented help. I will not think twice to recommend your site to any individual who desires guidance about this subject.

  20. 5 Killer Quora Answers On Malpractice Attorneys malpractice Attorney

  21. Ismaelfer表示:

    Good day! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading through your blog posts. Can you suggest any other blogs/websites/forums that cover the same subjects? Thanks a lot!
    http://www.musey-uglich.ru

  22. Kbqfna表示:

    vasotec brand – buy zovirax sale zovirax ca

  23. Don’t Buy Into These “Trends” Concerning Best Slots hacksaw Slots casino games

  24. What Motor Vehicle Lawsuit Is Your Next Big Obsession motor vehicle accident Lawsuit

  25. DavdidApari表示:

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

  26. Hi. I found your blog using msn. This can be a really well written article. I’ll be guaranteed to bookmark it are available returning to read much more of your useful info. Thanks for the post. I am going to certainly return.

  27. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?

  28. Lhaneevige表示:

    Thank you, I have recently been searching for information about this subject for a while and yours is the greatest I’ve discovered so far. However, what concerning the bottom line? Are you positive concerning the supply?
    http://http://musey-uglich.ru/

發佈留言

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