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...

6,140 Responses

  1. JamesBak表示:

    cost doxycycline australia: doxycycline cap tab 100mg – doxycycline cost canada

  2. I absolutely love your website.. Pleasant colors & theme. Did you build this amazing site yourself? Please reply back as I’m trying to create my own personal site and would like to learn where you got this from or exactly what the theme is named. Kudos.

  3. That is a very good tip especially to those new to the blogosphere. Brief but very precise information… Many thanks for sharing this one. A must read article!

  4. Lazrivm表示:

    Здравствуйте!
    Мы готовы предложить дипломы любой профессии по выгодным ценам.
    http://www.cyber-lynk.com/blog/2024/06/30/купить-диплом-онлайн/

  5. 博彩论坛表示:

    Very good info. Lucky me I discovered your site by accident (stumbleupon). I’ve bookmarked it for later!

  6. Uazrire表示:

    Добрый день!
    Заказать диплом любого университета.
    rst.adk.audio/company/personal/user/259/forum/message/1929/1953/

  7. Mesothelioma and other asbestos claim-related illnesses take a long time to develop,
    which can complicate the statute of limitations for filing a lawsuit.
    A knowledgeable attorney can help patients
    determine their deadlines and file within them.

  8. You’ve made some decent points there. I checked on the net for more info about the issue and found most people will go along with your views on this site.

  9. JamesBak表示:

    amoxicillin discount: amoxicillin canada price – ampicillin amoxicillin

  10. Dnrtsxs表示:

    Добрый день!
    Купить документ университета можно в нашей компании в Москве.
    asxdiplomik.com/kupit-diplom-krasnoyarsk
    Хорошей учебы!

  11. This is the perfect site for anyone who really wants to find out about this topic. You know a whole lot its almost tough to argue with you (not that I personally will need to…HaHa). You definitely put a new spin on a topic which has been discussed for many years. Wonderful stuff, just great.

  12. 15 Reasons Why You Shouldn’t Ignore Cheap Bunk Beds For Kids
    kids bunk bed sale

  13. Trefwmc表示:

    Здравствуйте!
    Купить диплом старого образца, можно ли это сделать по быстрой схеме?
    boosty.to/zukunft2/posts/cc9b2ee9-289d-4320-94e0-1fde4e3749a4
    Будем рады вам помочь!.

  14. Mazrjcr表示:

    Привет!
    Можно ли быстро купить диплом старого образца и в чем подвох?
    http://www.lafornacella.com/диплом-специалиста-2014-2024-фото/

  15. Stop Squeaking! Align Yourself For Business Success! 소녀 에볼루션 티어표

  16. 36035372.xyz表示:

    How To Recognize The Integrated Fridge Freezer Side By Side That’s Right For You
    36035372.xyz

  17. JamesBak表示:

    buy cheap clomid prices: buying generic clomid without dr prescription – where to buy generic clomid tablets

  18. Unsecured Signature Loans – The Best Way To Know Your Spending Limits
    디딤돌 대출

  19. Everyone loves it when folks get together and share ideas. Great blog, keep it up.

  20. Lazrmeu表示:

    Привет, друзья!
    Где купить диплом специалиста?
    Купить диплом о высшем образовании.
    3drus.ru/forum/topic_34877

  21. Eanrucf表示:

    Здравствуйте!
    Мы изготавливаем дипломы любой профессии по приятным ценам.
    grad-khv.ru/kak-kupit/

  22. ThomasDet表示:

    https://clomiddelivery.pro/# where buy clomid without insurance

  23. Dnrtgpn表示:

    Привет!
    Приобрести документ ВУЗа вы имеете возможность у нас.
    diplomasx24.ru/kupit-diplom-magistra
    Успехов в учебе!

  24. mybusness.com表示:

    Online Casinos And The Systems Myth 프라그마틱 데모,
    mybusness.com,

  25. AaronBuh表示:

    Компания Септик-Нара-купить септик для дачи
    занимается продажей, установкой и обслуживанием септиков в Наро-Фоминске Наро-Фоминском районе. Основное направление деятельности нашей компании именно установка под ключ септиков любых видов и размеров. С момента основания нашей компании, мы произвели монтаж более 1000 септиков по Московской и Калужской области. Благодаря этому у нас огромный опыт работы с любыми станциями, представленными в нашем регионе!
    Если Вы решили купить септик для дома или дачи, мы с радостью поможем Вам с выбором модели, доставим и установим септик на вашем участке в кратчайшие сроки.
    Мы занимаемся продажей септиков таких марок: Топас Юнилос Астра Евролос Тверь Аквалос Дочиста Фекалов Волгарь Удача. Мы работаем напрямую с производителями септиков, поэтому Вы можете быть уверены, что не переплачиваете ни копейки. Вся продукция в нашей компании имеет соответствующие сертификаты и лицензии. Время выезда на осмотр, установки или привоза оборудования согласовывается с клиентами и выполняется в срок. Мы заботимся о своей репутации, поэтому выполняем работу надежно и быстро.
    Если Вы не знаете, какой септик больше всего Вам подходит, мы предоставим консультацию и выезд специалиста на Ваш участок абсолютно бесплатно!
    Благодаря приобретению качественных септиков в нашей компании, каждый клиент получает большое количество преимуществ:
    » компактные размеры и небольшой вес устройства;
    » доступная стоимость очистной установки;
    » быстрый и простой монтаж;
    » невысокая стоимость эксплуатации;
    » отсутствие неприятных запахов;
    » высокая производительность;
    » длительный срок эксплуатации;
    » высокая степень очистки;
    » практически полностью автономный режим работы.

  26. Hi, I do think your site could possibly be having internet browser compatibility issues. When I take a look at your blog in Safari, it looks fine however, when opening in IE, it’s got some overlapping issues. I merely wanted to give you a quick heads up! Apart from that, great website!

  27. ThomasDet表示:

    http://paxloviddelivery.pro/# paxlovid for sale

  28. Lazrgdp表示:

    Добрый день!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
    toplentanews.ru/oformlenie-diploma-onlayn-za-neskolko-shagov

發佈留言

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