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

  1. You completed a few fine points there. I did a search on the matter and found mainly persons will have the same opinion with your blog.

  2. Great articles and great layout. Your blog post deserves all of the positive feedback it’s been getting.

  3. When I originally commented I clicked the -Notify me when new surveys are added- checkbox now when a comment is added I receive four emails with the exact same comment. Could there be any way you are able to remove me from that service? Thanks!

  4. It is really good post, but I don’t see everything completely clear, especially for someone not involved with that topic. Anyway very interesting in my experience.

  5. Bridgette表示:

    Guide To CSGO Cases New: The Intermediate Guide In CSGO
    Cases New csgo cases – Bridgette

  6. https://Dr-nona.ru – доктор Нона

  7. Quentin表示:

    Responsible For An Slot Demo Pragmatic Zeus
    Hades Budget? 12 Top Ways To Spend Your Money Quentin

  8. 7 Things About Free Casino Slots You’ll Kick Yourself For Not Knowing online casino slots

  9. i do paid online surverys and also monetize my blogs, both are good sources of passive income”

  10. Merely wanna state that this is very helpful , Thanks for taking your time to write this.

  11. Aw, this was a really nice post. In concept I wish to put in writing like this additionally ?taking time and precise effort to make a very good article?however what can I say?I procrastinate alot and by no means seem to get one thing done.

  12. Nice post. I learn something tougher on different blogs everyday. It will always be stimulating to study content off their writers and exercise a specific thing from their store. I’d would prefer to use some with all the content in my blog regardless of whether you don’t mind. Natually I’ll provide a link for your web weblog. Thank you for sharing.

  13. The next time I learn a weblog, I hope that it doesnt disappoint me as much as this one. I imply, I know it was my choice to read, but I really thought youd have one thing attention-grabbing to say. All I hear is a bunch of whining about one thing that you would fix in the event you werent too busy looking for attention.

  14. Get to know why News means very much to us.

  15. After research a number of of the weblog posts on your web site now, and I really like your means of blogging. I bookmarked it to my bookmark website listing and will probably be checking back soon. Pls try my web page as well and let me know what you think.

  16. There is noticeably a lot of money to understand this. I assume you have made particular nice points in functions also.

  17. An intriguing discussion might be priced at comment. I do think you should write much more about this topic, may well certainly be a taboo subject but typically consumers are insufficient to communicate on such topics. Yet another. Cheers

  18. Can I simply say what a relief to seek out somebody who actually knows what theyre speaking about on the internet. You definitely know the way to bring a problem to mild and make it important. More folks have to read this and understand this aspect of the story. I cant believe youre no more common since you positively have the gift.

  19. Spot lets start work on this write-up, I actually feel this site requirements considerably more consideration. I’ll oftimes be once again to see additional, thanks for that information.

  20. I recognize there exists a great deal of spam on this blog site. Do you need help cleaning them up? I can help among courses!

  21. Absolutely composed subject matter, thankyou for information .

  22. Thanks for this excellent article. One other thing is that a lot of digital cameras come equipped with the zoom lens that enables more or less of your scene to get included by means of ‘zooming’ in and out. All these changes in concentration length are usually reflected while in the viewfinder and on significant display screen right at the back of the specific camera.

  23. I am happy that I observed this weblog , just the right information that I was looking for! .

  24. I am usually to blogging and i genuinely appreciate your content regularly. This great article has really peaks my interest. My goal is to bookmark your web site and keep checking for brand new details.

  25. I have been checking out some of your articles and i must say pretty good stuff. I will definitely bookmark your blog.

  26. I know which Sage will not be upsetting demise with the appearance, and thus concerns about his or her country’s will fall.

  27. Thanks for your article. I would like to comment that the very first thing you will need to do is check if you really need repairing credit. To do that you simply must get your hands on a copy of your credit rating. That should never be difficult, considering that the government necessitates that you are allowed to get one cost-free copy of your real credit report yearly. You just have to check with the right people. You can either look at website for that Federal Trade Commission and also contact one of the major credit agencies directly.

  28. I would really like you to become a guest poster on my blog.”`,”;

  29. My brother recommended I might like this web site. He was totally right. This post actually made my day. You cann’t imagine simply how much time I had spent for this information! Thanks! xrumer

  30. A thoughtful opinion and ideas I will use on my website. You’ve obviously spent a lot of time on this. Thank you!

發佈留言

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