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

  1. Lazrzml表示:

    Привет!
    Купить диплом ВУЗа.
    diplomman.ru/kupit-svidetelstva

  2. Trefphh表示:

    Здравствуйте!
    Официальная покупка диплома вуза с сокращенной программой в Москве
    mans-diplomasxx.ru/kupit-diplom-ekaterinburg
    Рады помочь!.

  3. Diplomi_zdEa表示:

    Привет!
    Заказать документ университета вы имеете возможность у нас в столице.
    diplomrushkan.ru

  4. Diplomi_xmEa表示:

    Добрый день!
    Заказать документ университета вы можете в нашей компании в столице.
    rushkas-diplomyxx.ru

  5. check my site表示:

    You’ve made some good points there. I checked on the web for additional information about the issue and found most people will go along with your views on this web site.

  6. Samueldub表示:

    https://sildenafil.llc/# viagra without prescription

  7. Lazrykj表示:

    Привет, друзья!
    Мы изготавливаем дипломы любых профессий по приятным тарифам.
    rushkas-diplom.ru/attestat-za-11-klass

  8. Tesha表示:

    Mercedes Key Tools To Ease Your Day-To-Day Life replacement mercedes car
    key [Tesha]

  9. Trefadm表示:

    Добрый день!
    Приобретение школьного аттестата с официальным упрощенным обучением в Москве
    diploms-man.ru/attestat-za-9-klass
    Будем рады вам помочь!.

  10. Ethel表示:

    10 Facts About Auto Lock Smiths That Make You Feel Instantly The Best Mood mobile auto locksmiths
    (Ethel)

  11. Georgedrync表示:

    generic cialis without prescription: Generic Tadalafil 20mg price – is there a legal generic cialis made in the united states

  12. tubidy表示:

    Having read this I thought it was extremely enlightening. I appreciate you taking the time and effort to put this information together. I once again find myself spending way too much time both reading and posting comments. But so what, it was still worth it.

  13. Mazrlsu表示:

    Привет!
    Пошаговая инструкция по официальной покупке диплома о высшем образовании
    rushkadiplomik.ru

  14. Sazrccf表示:

    Привет!
    Диплом специалиста
    p99946c6.beget.tech/2024/07/19/vash-diplom-bez-lishnih-hlopot

  15. Georgedrync表示:

    real viagra without a doctor prescription: Buy Viagra online in USA – viagra pills

  16. Diplomi_wrEa表示:

    Добрый день!
    Заказать документ о получении высшего образования можно в нашей компании.
    rushkas-diplomy.ru

  17. Samueldub表示:

    http://tadalafil.auction/# find cheapest cialis pills

  18. sunwin表示:

    I’d like to thank you for the efforts you have put in writing this blog. I really hope to see the same high-grade blog posts by you later on as well. In fact, your creative writing abilities has encouraged me to get my very own site now 😉

  19. Lazrpdt表示:

    Привет, друзья!
    Мы готовы предложить дипломы любых профессий по доступным ценам.
    rushkadiplomiks.ru/kupit-diplom-ekaterinburg

  20. Trefjik表示:

    Добрый день!
    Как официально купить диплом вуза с упрощенным обучением в Москве
    diploms-man.ru/kupit-diplom-novosibirsk
    Рады оказать помощь!.

  21. 10 Things That Your Family Teach You About Double Glazing Doctor Near Me Double glazing doctor near me

  22. see this here表示:

    I needed to thank you for this fantastic read!! I certainly loved every bit of it. I’ve got you book-marked to look at new things you post…

  23. Mazrxan表示:

    Привет!
    Официальная покупка диплома вуза с упрощенной программой обучения
    arusak-diploms-srednee.ru/kupit-diplom-magistra

  24. OLaneevige表示:

    Why users still make use of to read news papers when in this technological world everything is presented on net?

    https://tehnoprice.in.ua/kley-dlya-fary

  25. I like this website very much, Its a very nice post to read and find information.

  26. EarnestAvada表示:

    I’m not sure exactly why but this website is loading extremely slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later and see if the problem still exists.

    https://ital-parts.com.ua/vysokoyakisne-sklo-korpusy-ta-skladovi-fary-dlya-bmw-5er

  27. Exactly where maybe you have discovered the source meant for the following write-up? Great reading through I’ve subscribed to your blog feed.

  28. Mazrcjn表示:

    Привет, друзья!
    Где и как купить диплом о высшем образовании без лишних рисков
    rushkadiplomik.ru

  29. A The Complete Guide To Cheap Anal Sex Toys From Start To Finish Male Ass sex toy

  30. An extremely good post. This post sums up for me just what this topic is all about and some of the major benefits that can be produced by knowing about it just like you. A friend once pointed out that you have a totally different approach when you do something for certain as opposed to when you’re simply just toying with it. In the case of this specific topic, I believe you’re taking, or start to go for, a more professional plus thorough approach to what and how you’re writing, which in turn helps you to continue to get better and help others who don’t know anything at all about what you have discussed here. Thank you.

發佈留言

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