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

  1. Hi there! I simply would like to give an enormous thumbs up for the great information you might have here on this post. I might be coming back to your weblog for more soon.

  2. WayneCoirl表示:

    mexican border pharmacies shipping to usa: mexican rx online – mexican rx online

  3. DominicJaw表示:

    medication from mexico pharmacy: medicine in mexico pharmacies – medicine in mexico pharmacies

  4. I like the way you conduct your posts. Yessir!

  5. Nelsonbluck表示:

    mexican border pharmacies shipping to usa: reputable mexican pharmacies online – medicine in mexico pharmacies

  6. Diplomi_npEa表示:

    Привет, друзья!
    Заказать документ университета можно в нашем сервисе.
    diplomyx.com/kupit-diplom-kazan

  7. A Peek In The Secrets Of Demo Slot Sweet Bonanza Xmas Sweet Bonanza Bonus Buy Demo

  8. Arnoldten表示:

    buying prescription drugs in mexico pharmacies in mexico that ship to usa mexican drugstore online

  9. Xazreqj表示:

    Добрый день!
    Покупка диплома о среднем полном образовании: как избежать мошенничества?
    landik-diploms-srednee.ru/kupit-diplom-saratov

  10. Manrntz表示:

    Привет!
    Купить документ ВУЗа
    ast-diplom.com/kupit-diplom-voronezh

  11. Reent表示:

    Death and Other Details (Hulu Disney+ Canada) has been cancelled after 1 season. Xumo is a media streaming service with over 180 free channels. It also gives you free reign over its multi-genre movie selection. If you’re looking for a completely hassle-free movie night, Xumo is well worth a gander — you don’t need to enter any payment details or even register to use it.  CP24 GO is an app developed by Bell Media that gives Bell TV customers complimentary access to CP24 content on demand through computers, iOS and Android devices. · ‘Feels like’ temperature that accounts for humidex and wind-chill · ‘Feels like’ temperature that accounts for humidex and wind-chill CP24 remains the de-facto “cable pulse” of Toronto, even if they no longer go by that title. The fact that many people in Toronto still wrongly believe it to be a Citytv operation shows how powerful the original branding was back in 1998.
    https://paxtonhxin000099.post-blogs.com/49125521/search-social-media-name-availability
    All funds in your 2024 Birdland Flex Membership must be used for tickets during the 2024 regular season and are not eligible for 2024 Opening Day or 2024 Postseason. Access to your funds for 2024 will begin in the offseason prior to single game tickets going on sale to the general public. **Nintendo Switch Online membership (sold separately) and Nintendo Account required for online play. Not available in all countries. Internet access required for online features. Terms apply. nintendo switch-online Stream YouTube TV to your TV using Google Chromecast, TVs with Chromecast built-in like Android TV, AirPlay for Apple TV, or Google Smart Displays. We don’t simply accept a TV’s out-of-the-box settings, of course. We don’t go down the route of professionally calibrating the TVs we test (you shouldn’t have to have your TV professionally calibrated in order to see it at its best), but we do spend hours testing and adjusting the picture settings and processing modes – using a mix of test patterns and real-world content – until we’re confident that we’re getting the best performance possible.

  12. Hey just wanted to give you a quick heads up. The text in your article seem to be running off the screen in Chrome. I’m not sure if this is a format issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the problem resolved soon. Thanks

  13. WayneCoirl表示:

    mexican online pharmacies prescription drugs: purple pharmacy mexico price list – mexican mail order pharmacies

  14. DominicJaw表示:

    mexico drug stores pharmacies: mexico drug stores pharmacies – mexican rx online

  15. What are you stating, man? I recognize everyones got their own opinion, but really? Listen, your website is cool. I like the hard work you put into it, specifically with the vids and the pics. But, come on. Theres gotta be a better way to say this, a way that doesnt make it seem like most people here is stupid!

  16. Dnrtbqj表示:

    Привет!
    Купить документ института можно в нашей компании.
    diplomyx.com/kupit-diplom-o-srednem-obrazovanii
    Успешной учебы!

  17. Guide To Slot Princess Demo: The Intermediate Guide For Slot Princess Demo slot Princess demo

  18. Hey! I simply wish to give a huge thumbs up for the good information you have right here on this post. I might be coming back to your weblog for extra soon.

  19. Nelsonbluck表示:

    pharmacies in mexico that ship to usa: buying prescription drugs in mexico – purple pharmacy mexico price list

  20. Samuel表示:

    11 “Faux Pas” That Actually Are Okay To Do With Your Locksmiths For Cars Near Me locksmith car
    key replacement cost (Samuel)

  21. Treflms表示:

    Привет, друзья!
    Аттестат школы купить официально с упрощенным обучением в Москве
    jubileetrip.com/2024/07/12/купить-диплом-проверенные-способы
    Поможем вам всегда!.

  22. The 10 Scariest Things About Dangerous Drugs Law Firms
    dangerous Drugs law firm

  23. tubidy表示:

    You should be a part of a contest for one of the most useful blogs online. I will highly recommend this web site!

  24. Arnoldten表示:

    mexico drug stores pharmacies best online pharmacies in mexico reputable mexican pharmacies online

  25. the travel packages that i have seen on the internet are sometimes oversold, they are cheap yet the inclusions sucks..

  26. WayneCoirl表示:

    mexico pharmacies prescription drugs: mexico pharmacies prescription drugs – pharmacies in mexico that ship to usa

  27. I have read a few good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a wonderful informative website.

  28. DominicJaw表示:

    pharmacies in mexico that ship to usa: purple pharmacy mexico price list – mexico drug stores pharmacies

  29. RichardWrifs表示:

    http://mexicandeliverypharma.com/# п»їbest mexican online pharmacies

  30. the doctor said that we have an allergic baby that is why we choose hypoallergenic baby clothes“

發佈留言

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