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

  1. Have you investigated adding some videos for your article? I think it will really enhance my understanding

  2. Wow, this is really interesting reading. I am glad I found this and got to read it. Great job on this content. I like it.

  3. What Is The Best Way To Spot The CS GO Weapon Case That’s Right For
    You Esports 2013 winter case

  4. The Companies That Are The Least Well-Known To Keep An Eye
    On In The Veterans Disability Attorney Industry veterans disability Lawsuits

  5. Why We Our Love For Main Zeus Demo (And You Should Also!) Zeus Of Olympus Demo

  6. build表示:

    How To Build A Successful GSA SER Links If You’re Not Business-Savvy build

  7. Tnaqfa表示:

    dulcolax 5 mg generic – brand dulcolax 5mg liv52 10mg cheap

  8. Mercedes Keys表示:

    14 Cartoons About Keys For Mercedes That’ll Brighten Your Day Mercedes Keys

  9. 15 Presents For Your Are CSGO Cases Predetermined Lover In Your Life operation hydra Case

  10. Hello! I just now wish to provide a huge thumbs up for the great information you could have here during this post. We are coming back to your website for further soon.

  11. ADHD Diagnosis Private UK: A Simple Definition Private Adhd Assessment Adults

  12. An intriguing discussion will probably be worth comment. There’s no doubt that that you simply write regarding this topic, it will not certainly be a taboo subject but usually consumers are not enough to communicate on such topics. An additional. Cheers

  13. The Main Issue With Cheap Under Counter Fridge, And How To Fix It
    fridge under Counter

  14. Thanks for this post. I definitely agree with what you are saying. I have been talking about this subject a lot lately with my mother so hopefully this will get him to see my point of view. Fingers crossed!

  15. 15 Reasons Why You Shouldn’t Be Ignoring SEO Near London affordable seo near me

  16. An intriguing discussion may be worth comment. I’m sure you should write much more about this topic, may well be described as a taboo subject but generally folks are too little to chat on such topics. An additional. Cheers

  17. There a few intriguing points soon enough on this page but I do not determine if I see these people center to heart. There is certainly some validity but I’ll take hold opinion until I investigate it further. Excellent article , thanks and then we want a lot more! Added to FeedBurner at the same time

  18. Generally I do not read post on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, quite nice post.

  19. I have been absent for some time, but now I remember why I used to love this website. Thanks , I¡¦ll try and check back more frequently. How frequently you update your site?

  20. Really very good information web page. I have to admit that we’re definitely warm the idea

  21. Hello! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no back up. Do you have any methods to stop hackers?

  22. Oh my goodness! a great post dude. Thanks a ton Even so We are experiencing issue with ur rss . Don’t know why Not able to subscribe to it. Will there be any person acquiring identical rss dilemma? Anybody who knows kindly respond. Thnkx

  23. Your positions normally have a lot of really up to date info. Where do you come up with this? Just stating you are very innovative. Thanks again

  24. Hi! Aw, this was a really nice post. In idea I would like to put in writing like this additionally – taking time and actual effort to make a very good article… but what can I say… I procrastinate alot and by no means seem to get something done.

  25. My personal sis recommended me personally regarding your web website and exactly how excellent it is. She’s proper, I am genuinely impressed using the composing and slick design. It appears in my experience you’re simply scratching the surface when it comes to what you might achieve, however you’re off to a good start!

  26. Sweet web site , super style and design , really clean and use pleasant.

  27. This could be the right weblog for anyone who wishes to learn about this topic. You recognize a whole lot its practically hard to argue on hand (not that I actually would want…HaHa). You certainly put the latest spin on the topic thats been discussing for a long time. Fantastic stuff, just fantastic!

  28. When I originally commented I clicked the -Notify me when new surveys are added- checkbox and already whenever a comment is added I am four emails sticking with the same comment. Can there be any way you are able to eliminate me from that service? Thanks!

  29. french translation is kind of hard at first but if you get used to it, then it is easy**

  30. This is the correct weblog for anyone who hopes to be made aware of this topic. You know so much its nearly tough to argue on hand (not that I really would want…HaHa). You definitely put a fresh spin using a topic thats been revealed for many years. Wonderful stuff, just excellent!

發佈留言

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