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

  1. JamesBes表示:

    пояснения
    KENT

  2. AlbertNer表示:

    https://kamapharm.com/# Kama Pharm
    prednisone online for sale

  3. JamesBes表示:

    посетить веб-сайт
    vodkabet

  4. AlbertNer表示:

    http://semapharm24.com/# semaglutide tablets for weight loss
    prednisone 200 mg tablets

  5. LarryLog表示:

    Pred Pharm: where to buy prednisone without prescription – Pred Pharm

  6. DanielZek表示:

    http://predpharm.com/# PredPharm
    Kamagra 100mg

  7. What Is The Window Doctor Near Me Term And How To Use It The Window Doctor Near Me

  8. Waltererync表示:

    Pred Pharm: Pred Pharm – prednisone medication

  9. LarryLog表示:

    cheap semaglutide pills: Sema Pharm 24 – buy rybelsus online

  10. AlbertNer表示:

    https://semapharm24.com/# rybelsus semaglutide tablets
    can you buy prednisone over the counter in canada

  11. DanielZek表示:

    https://semapharm24.com/# Sema Pharm 24
    buy kamagra online usa

  12. Waltererync表示:

    Pred Pharm: PredPharm – 50 mg prednisone tablet

  13. AlbertNer表示:

    https://cytpharm.shop/# buy cytotec
    buy prednisone online australia

  14. PublicKa表示:

    Работа курьером в Купер: надёжный путь к стабильному доходу

    Купер — это компания, которая предоставляет работу курьером с удобным графиком, высоким доходом и возможностью профессионального роста. Мы сотрудничаем с лидерами рынка доставки, поэтому наши курьеры всегда обеспечены заказами и поддержкой.

    На сайте Как стать курьером РІ Купер вы можете найти всю информацию о работе, подать заявку и узнать об условиях трудоустройства. У нас есть вакансии для пеших курьеров, велокурьеров и водителей-курьеров по всей России.

    Почему стоит выбрать Купер?

    – Стабильный доход: курьеры зарабатывают от 3 000 до 5 000 рублей в день, в зависимости от количества выполненных заказов.
    – Удобный график: вы сами выбираете, когда работать, что идеально подходит для студентов, самозанятых и тех, кто ищет гибкость.
    – Простота оформления: подача заявки и оформление документов занимает минимум времени.
    – Безопасность: мы заботимся о здоровье наших сотрудников и предоставляем все необходимые инструкции для безопасной доставки.

    Как устроиться курьером в Купер?

    1. Заполните заявку на сайте. Укажите свои данные, город и тип транспорта (если есть).
    2. Пройдите короткое собеседование с нашим менеджером. Мы уточним детали и расскажем о графике, доходах и обязанностях.
    3. Подготовьте документы: паспорт, СНИЛС и, при необходимости, медицинскую книжку.
    4. Пройдите обучение: мы покажем, как пользоваться приложением для курьеров, выбирать выгодные заказы и эффективно работать.
    5. Начните работу: вы можете принимать заказы сразу после активации профиля.

    Какие заказы выполняют курьеры?

    Наши курьеры доставляют всё: от продуктов и лекарств до документов и посылок. Мы сотрудничаем с популярными сервисами доставки, что обеспечивает высокий объём заказов.

    Преимущества для наших сотрудников

    – Возможность зарабатывать больше за счёт бонусов и выполнения срочных заказов.
    – Стабильная поддержка от компании на всех этапах работы.
    – Возможность выбора районов и маршрутов доставки.

    Как подать заявку?

    Перейдите на сайт, заполните простую анкету, и мы свяжемся с вами в ближайшее время. Наш менеджер бесплатно проконсультирует вас, расскажет обо всех условиях и поможет начать зарабатывать уже сегодня.

    Работа курьером в Купер — это ваш шанс получить стабильный доход, свободный график и работу, которая подстраивается под ваш стиль жизни. Присоединяйтесь к нашей команде и начните зарабатывать уже сегодня!

  15. LarryLog表示:

    semaglutide tablets price: buy rybelsus online – buy semaglutide

  16. DanielZek表示:

    https://semapharm24.shop/# SemaPharm24
    super kamagra

  17. Christine表示:

    Five Killer Quora Answers To Second Hand Containers For Sale UK second hand containers
    for sale uk (Christine)

  18. Waltererync表示:

    Kama Pharm: п»їkamagra – Kama Pharm

  19. AlbertNer表示:

    https://kamapharm.com/# Kama Pharm
    prednisone 20 mg without prescription

  20. LarryLog表示:

    buy rybelsus online: buy rybelsus online – semaglutide tablets store

  21. DanielZek表示:

    https://predpharm.shop/# buying prednisone on line
    cheap kamagra

  22. AlbertNer表示:

    https://dappharm.com/# dapoxetine price
    where can i buy prednisone

  23. Waltererync表示:

    cheap semaglutide pills: Sema Pharm 24 – rybelsus semaglutide tablets

  24. The Top Reasons People Succeed On The Replacement Double Glazing
    Sealed Units Industry double glazing sealed unit replacement prices

  25. Zhbsfh表示:

    zithromax 500mg oral – purchase nebivolol without prescription oral nebivolol

  26. LarryLog表示:

    prednisone 5 tablets: Pred Pharm – PredPharm

  27. Petervop表示:

    Understanding the Aave Protocol
    The Aave Protocol is revolutionizing the decentralized finance (DeFi) space with its unique approach to crypto lending and borrowing. Whether you’re a seasoned investor or new to the world of cryptocurrencies, Aave offers a robust platform for managing your digital assets.
    aave lending
    What is Aave?
    Aave, which means ‘ghost’ in Finnish, is a non-custodial liquidity protocol. It allows users to earn interest on deposits and borrow assets. Aave is known for its wide range of supported cryptocurrencies and features that enhance the security and flexibility of crypto transactions.

    Key Features of Aave Protocol
    Flash Loans: Aave introduced the concept of flash loans, which are borrowed and repaid within a single transaction. This feature is useful for arbitrage opportunities and collateral swaps.
    Security: Aave is audited by leading blockchain security firms, ensuring the safety of user funds.
    Rate Switching: Users can switch between stable and variable interest rates, offering flexibility based on market conditions.
    Wide Asset Support: Aave supports multiple cryptocurrencies including Ethereum (ETH), DAI, and more.
    How to Get Started with Aave
    Getting started with Aave is straightforward:

    Set Up a Wallet: Use a compatible crypto wallet like MetaMask.
    Connect to Aave: Visit the Aave website and connect your wallet.
    Deposit Crypto: Choose from supported cryptocurrencies to deposit into the Aave Protocol.
    Start Earning or Borrowing: Once your crypto is deposited, you can start earning interest or borrowing assets instantly.
    Advantages of Using Aave
    There are several reasons why Aave stands out in the world of DeFi:

    Non-Custodial: Users maintain control over their funds.
    Highly Secure: Regular audits and community governance enhance security.
    Innovative Products: Pioneering features like flash loans provide unparalleled opportunities.
    In conclusion, the Aave Protocol offers a revolutionary platform for anyone looking to explore the potential of decentralized finance. Whether you’re earning interest or borrowing assets, Aave provides a secure and flexible experience.

  28. DanielZek表示:

    https://kamapharm.com/# Kama Pharm
    buy Kamagra

  29. Waltererync表示:

    buy priligy: dap pharm – DapPharm

發佈回覆給「AlbertNer」的留言 取消回覆

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