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

  1. Jerryacast表示:

    https://fastfromindia.com/# Fast From India
    india pharmacy mail order

  2. ThomasGooks表示:

    canadian pharmacy
    http://expresscanadapharm.com/# Express Canada Pharm
    canadian pharmacy victoza

  3. FrankKen表示:

    детский хоккей – политическая ситуация Украина, китайские дорамы Казахстан

  4. Aaroncrasy表示:

    top 10 online pharmacy in india: indian pharmacy online – india online pharmacy

  5. Henryutisa表示:

    india pharmacy: Fast From India – Fast From India

  6. FrankKen表示:

    обзоры детских товаров Казахстан – кредитное рабство, спортивные клубы

  7. Jerrybrusa表示:

    Стремитесь к ТОП Яндекса в 2025 г. благодаря нашему Телеграм-каналом!

    Что именно ты найдете в нашем Telegram-канале:

    Переходите в наш Телеграм-канал, чтобы:

    Получить бесплатные советы.
    Узнать расценки за услуги.
    Приобрести эффективное продвижение.
    Оплатить сервисы каким угодно подходящим вариантом.

    https://telegra.ph/prodvizhenie-biznesa-vkontakte-sistemnyj-podhod-03-02-4

    Наша команда поможем тебе вывести твой веб-сайт в вершину Yandex! Не стоит упускать твой шанс!

  8. Henryutisa表示:

    buy prescription drugs from india: Fast From India – buy prescription drugs from india

  9. FrankKen表示:

    права инвалидов Казахстан – вакансии Казахстан, истории материнства Казахстан

  10. ThomasGooks表示:

    canadian pharmacy 365
    https://expresscanadapharm.com/# Express Canada Pharm
    best canadian pharmacy

  11. ThomasGooks表示:

    best mail order pharmacy canada
    https://expresscanadapharm.shop/# canadian pharmacy 365
    canadian pharmacy victoza

  12. Jerryacast表示:

    https://fastfromindia.shop/# Online medicine home delivery
    cheapest online pharmacy india

  13. iwin表示:

    Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  14. JamesMax表示:

    indian pharmacy paypal Fast From India Fast From India
    top 10 pharmacies in india

  15. ThomasGooks表示:

    canada rx pharmacy
    https://expresscanadapharm.com/# Express Canada Pharm
    canadian pharmacy service

  16. FrankKen表示:

    выпечка Казахстан – медицинская помощь для инвалидов Казахстан, экономические программы Казахстан

  17. ThomasGooks表示:

    canadian pharmacy 365
    https://expresscanadapharm.com/# canadianpharmacy com
    online canadian pharmacy

  18. FrankKen表示:

    кино Казахстана – лучшие курорты для казахстанцев ??, строительство бани Казахстан

  19. iwin club表示:

    Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  20. Beryl表示:

    14 Common Misconceptions Concerning Robotic Hoover robotic hoovers [Beryl]

  21. JamesMax表示:

    indian pharmacies safe Fast From India Fast From India
    india pharmacy mail order

  22. Aaroncrasy表示:

    Fast From India: Fast From India – world pharmacy india

  23. Jerryacast表示:

    https://fastfromindia.com/# buy prescription drugs from india
    indian pharmacy

  24. Тут можно преобрести создать сайт медицинской клиники создание сайта клиники

  25. Aaroncrasy表示:

    Fast From India: top online pharmacy india – Fast From India

  26. b52 club表示:

    Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  27. ThomasGooks表示:

    buy canadian drugs
    https://expresscanadapharm.shop/# certified canadian pharmacy
    canadian pharmacy drugs online

  28. Henryutisa表示:

    п»їlegitimate online pharmacies india: top 10 pharmacies in india – Fast From India

  29. ThomasGooks表示:

    legitimate canadian pharmacy online
    https://expresscanadapharm.com/# Express Canada Pharm
    legitimate canadian pharmacy online

  30. 10 Things That Your Family Teach You About Aluminium Windows Doors Aluminium windows doors – https://mccarty-frederick-2.technetbloggers.de/

發佈回覆給「https://mccarty-frederick-2.technetbloggers.de/」的留言 取消回覆

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