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

14,072 Responses

  1. WillieSor表示:

    Площадка кракен – кракен официальный сайт, Kra31.cc

  2. WilliamNop表示:

    Kamagra: kamagra kopen nederland – kamagra 100mg kopen

  3. Kennethslity表示:

    http://generic100mgeasy.com/# Generic100mgEasy

  4. xhbkqfsoj表示:

    Only casino fans who have claimed the first four deposit bonuses included in the Welcome Package are eligible for the no deposit promotion. What is more, the bonus is available to players who select the Red Casino section. If you join Intertops Red Casino, you will never be short of action. To enhance its players’ performance, the casino operator offers a generous Welcome Package that covers the first four deposits. Once you have claimed all match deposit bonuses, you will have the exclusive opportunity to benefit from a $55 no deposit bonus. Whether you opt for a deposit code or a no deposit code, press “Next” to continue through the process until the bonus is credited to your account. In the event that your bonus is not automatically activated, you can contact support within 48 hours of your deposit to have it manually added.
    https://mahajakindustry.com/jogue-o-acabamento-jetx-apontar-cbet-com-dinheiro-efetivo/
    A no deposit bonus code is a code you need to use to activate the offer. Not all bonus offers have a code but when they do, they should be easy to find at the casino site or here at Casino.org. This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Cookies set by the website owner (in this case, ) are called “first-party cookies.” Cookies set by parties other than the website owner are called “third-party cookies.” Third-party cookies enable third-party features or functionality to be provided on or through the website (e.g., advertising, interactive content, and analytics). The parties that set these third-party cookies can recognize your computer both when it visits the website in question and also when it visits certain other websites.

  5. This is a great article!

  6. TerryDus表示:

    https://generic100mgeasy.com/# best price for viagra 100mg

  7. WilliamNop表示:

    buy generic 100mg viagra online: Generic100mgEasy – Viagra without a doctor prescription Canada

  8. Dwayneseisa表示:

    buy generic 100mg viagra online Generic100mgEasy buy generic 100mg viagra online

  9. GregoryJough表示:

    Generic 100mg Easy: Generic 100mg Easy – Cheap generic Viagra online

  10. MarvinInget表示:

    кракен официальный сайт – кракен магазин, kra31 at

  11. Kennethslity表示:

    https://kamagrakopen.pro/# Kamagra Kopen

  12. TerryDus表示:

    https://tadalafileasybuy.com/# Tadalafil Easy Buy

  13. Kennethslity表示:

    http://tadalafileasybuy.com/# TadalafilEasyBuy.com

  14. MarvinInget表示:

    Kra31.at – кракен вход, kraken market

  15. WilliamNop表示:

    Tadalafil Easy Buy: Tadalafil Easy Buy – TadalafilEasyBuy.com

  16. MarvinInget表示:

    кракен зеркало – kra31 cc, кракен сайт

  17. TerryDus表示:

    http://tadalafileasybuy.com/# cialis without a doctor prescription

  18. Hệ thống bảo mật của okadabooks.com đảm bảo an toàn tuyệt đối cho người truy cập.

  19. 1xbet_nmPi表示:

    Погрузитесь в азарт с 1xbet, прямо сейчас.

    Ставки на спорт с 1xbet, самые выгодные коэффициенты.

    Получите бонусы на первую ставку с 1xbet, промоакции.

    1xbet – идеальное место для спортивных ставок, получайте.

    1xbet – ваш портал в мир лайв-ставок, вы всегда на шаг впереди.

    1xbet – это огромное количество спортивных событий, и выигрывайте.

    Обширные рынки на 1xbet, от футбола до тенниса.

    1xbet дарит вам возможность следить за играми, погрузитесь в атмосферу.

    1xbet – получите свои выигрыши мгновенно, действуйте быстро.

    Получите инсайдерскую информацию с 1xbet, дайте себе преимущество.

    Ваши данные в безопасности с 1xbet, это важно.

    Не пропустите акционные предложения от 1xbet, воспользуйтесь шансом.

    Ставьте смело с 1xbet, выберите правильный путь.

    Получите помощь в любое время на 1xbet, мы рядом, чтобы помочь.

    1xbet – это не только ставки, но и конкурсы, примите участие.

    1xbet в вашем кармане, всегда под рукой.

    Используйте статистику и аналитику на 1xbet, это умная игра.

    Зарегистрируйтесь на 1xbet всего за несколько минут, доступ к азарту.

    Откройте новый уровень азартных игр с 1xbet, начните выигрывать.

    Заходите на 1xbet для эксклюзивных предложений, развивайте свои навыки.
    1xbet 1xbet .

  20. Trải nghiệm cá cược tại f168.com.co mượt mà, không giật lag.

  21. WilliamNop表示:

    Generic100mgEasy: Generic 100mg Easy – buy generic 100mg viagra online

  22. Cộng đồng người chơi tại 789p.page đông đảo, giao lưu sôi động.

  23. 1xbet_ijPi表示:

    Погрузитесь в азарт с 1xbet, прямо сейчас.

    Ставки на спорт с 1xbet, на рынке.

    1xbet предлагает щедрые бонусы, сегодня.

    Скорее ставьте на свои любимые команды с 1xbet, от ставок.

    Лайв-ставки с 1xbet – это захватывающе, ваши шансы на выигрыш увеличиваются.

    Всё для ваших ставок на 1xbet, создавайте.

    1xbet – это выбор на любой вкус, от любимых команд до редких событий.

    Смотрите матчи в режиме реального времени с 1xbet, погрузитесь в атмосферу.

    Деньги на вашем счете с 1xbet за считанные минуты, действуйте быстро.

    Получите инсайдерскую информацию с 1xbet, будьте всегда на шаг впереди.

    Ставьте с уверенностью на 1xbet, мы ценим вашу конфиденциальность.

    Промокоды и специальные предложения на 1xbet, максимизируйте свой выигрыш.

    Ставьте смело с 1xbet, выберите 1xbet для своей игры.

    Получите помощь в любое время на 1xbet, мы рядом, чтобы помочь.

    1xbet – это не только ставки, но и конкурсы, будьте в курсе событий.

    Ставьте в любое время и в любом месте с 1xbet, сделайте ставки на ходу.

    Ставьте на основе данных с 1xbet, будьте стратегом.

    Простая регистрация на 1xbet, приступайте к ставкам.

    Откройте новый уровень азартных игр с 1xbet, начните выигрывать.

    1xbet – это место для настоящих игроков, ставьте с умом.
    app 1xbet https://1xbet-login-egypt.com/ .

  24. bj88.name có hệ thống hoàn trả cược cực kỳ hấp dẫn.

  25. WillieSor表示:

    кракен открыть – кра сайт, кракен официальная ссылка

  26. MarvinInget表示:

    Kra30.cc – kra32.cc, kraken зеркало

  27. MarvinInget表示:

    кракен ссылка – кракен, kraken сайт

發佈留言

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