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

  1. BarryDof表示:

    http://rybelsus.shop/# rybelsus pill

  2. HaroldBig表示:

    ozempic coupon: ozempic online – buy ozempic pills online

  3. Профессиональный сервисный центр по ремонту сигвеев в Москве.
    Мы предлагаем: сигвей ремонт аккумулятора
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. Frankevild表示:

    http://rybelsus.shop/# buy semaglutide online

  5. kubet表示:

    I blog quite often and I genuinely thank you for your information. This article has truly peaked my interest. I am going to bookmark your blog and keep checking for new details about once a week. I opted in for your Feed as well.

  6. BarryDof表示:

    http://ozempic.art/# ozempic online

  7. Frankevild表示:

    https://rybelsus.shop/# cheapest rybelsus pills

  8. Профессиональный сервисный центр по ремонту электросамокатов в Москве.
    Мы предлагаем: ремонт самокатов москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. ZairobaMat表示:

    Ваша кредитная история не идеальна, и это мешает получить необходимый займ? Деньги на карту без проверок мгновенно предлагает микрокредиты до 30 000 рублей для всех, кто сталкивается с отказами в банках. Подписывайтесь на канал, чтобы узнать о самых актуальных предложениях от МФО, которые предоставляют деньги даже с просрочками. Надежность, оперативность и простота – всё это доступно уже сейчас.

  10. Way cool! Some extremely valid points! I appreciate you penning this write-up and also the rest of the site is also really good.

  11. HaroldBig表示:

    buy semaglutide online: rybelsus price – rybelsus price

  12. Jeremypag表示:

    ozempic generic buy ozempic pills online ozempic online

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

  14. Jeremypag表示:

    ozempic online ozempic cost ozempic coupon

  15. RamonRek表示:

    buy rybelsus online: buy semaglutide online – buy rybelsus online

  16. BarryDof表示:

    http://ozempic.art/# buy cheap ozempic

  17. RobertWaf表示:

    Arrowheads reveal the presence of a mysterious army in Europe’s oldest battle
    порно секс жесток
    Today, the lush, green valley surrounding the Tollense River in northeast Germany appears to be a serene place to appreciate nature.

    But to archaeologists, the Tollense Valley is considered Europe’s oldest battlefield.

    An amateur archaeologist first spotted a bone sticking out of the riverbank in 1996.

    A series of ongoing site excavations since 2008 has shown that the thousands of bones and hundreds of weapons preserved by the valley’s undisturbed environment were part of a large-scale battle 3,250 years ago.

    The biggest mysteries that researchers aim to uncover are why the battle occurred and who fought in it. These are questions that they are now one step closer to answering.
    ozens of bronze and flint arrowheads recovered from the Tollense Valley are revealing details about the able-bodied warriors who fought in the Bronze Age battle.

    The research team analyzed and compared the arrowheads, some of which were still embedded in the remains of the fallen. While many of these weapons were locally produced, some bearing different shapes came from a region that now includes modern Bavaria and Moravia.

    The outliers’ presence suggests that a southern army clashed with local tribes in the valley, and researchers suspect the conflict began at a key landmark along the river.

    Back to the future
    Scientists are harnessing the power of artificial intelligence to detect hidden archaeological sites buried below the sand of the sprawling Rub‘ al-Khali desert.

    The desert spans 250,000 square miles (650,000 square kilometers) on the Arabian Peninsula, and its name translates to “the Empty Quarter” in English. To unravel the secrets of the desolate terrain, researchers are combining machine learning with a satellite imagery technique that uses radio waves to spot objects that may be concealed beneath surfaces.

    The technology will be tested in October when excavations assess whether predicted structures are present at the Saruq Al Hadid complex in Dubai, United Arab Emirates.

    Separately, an AI-assisted analysis uncovered a trove of ancient symbols in Peru’s Nazca Desert, nearly doubling the number of known geoglyphs, or stone and gravel arranged into giant shapes that depict animals, humans and geometric designs.

  18. RamonRek表示:

    ozempic coupon: buy ozempic pills online – buy ozempic

  19. Профессиональный сервисный центр по ремонту планшетов в Москве.
    Мы предлагаем: замена стекла на планшете цена
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  20. Frankevild表示:

    https://ozempic.art/# buy cheap ozempic

  21. BarryDof表示:

    https://ozempic.art/# ozempic generic

  22. HaroldBig表示:

    rybelsus price: rybelsus cost – rybelsus pill

  23. Jeremypag表示:

    semaglutide online cheapest rybelsus pills rybelsus price

  24. Jeremypag表示:

    buy cheap ozempic buy cheap ozempic Ozempic without insurance

  25. Philiplet表示:

    Я уже несколько лет являюсь пайщиком кооператива “Бест Вей“, и все происходящее вокруг вызывает у меня чувство глубокого разочарования и недоумения. Наш кооператив всегда работал с открытостью и честностью, и теперь его обвиняют в мошенничестве? Это просто абсурд! Я видел, как много людей получили квартиры благодаря этому кооперативу, и у меня нет никаких сомнений в том, что он действовал добросовестно. Следственные органы действуют абсолютно произвольно, арестовывая людей, которые ничего не сделали плохого, в то время как настоящие преступники остаются на свободе. Меня поразило, как легко манипулируют мнением общественности, пытаясь убедить всех, что мы, пайщики, являемся жертвами. Это не что иное, как попытка прикрыть свои неудачи на фоне бездействия. Я буду продолжать поддерживать кооператив и защищать его интересы, потому что верю, что рано или поздно справедливость восторжествует.

  26. BarryDof表示:

    http://ozempic.art/# buy ozempic pills online

  27. Jeffreygef表示:

    Arrowheads reveal the presence of a mysterious army in Europe’s oldest battle
    анальный секс зрелых
    Today, the lush, green valley surrounding the Tollense River in northeast Germany appears to be a serene place to appreciate nature.

    But to archaeologists, the Tollense Valley is considered Europe’s oldest battlefield.

    An amateur archaeologist first spotted a bone sticking out of the riverbank in 1996.

    A series of ongoing site excavations since 2008 has shown that the thousands of bones and hundreds of weapons preserved by the valley’s undisturbed environment were part of a large-scale battle 3,250 years ago.

    The biggest mysteries that researchers aim to uncover are why the battle occurred and who fought in it. These are questions that they are now one step closer to answering.
    ozens of bronze and flint arrowheads recovered from the Tollense Valley are revealing details about the able-bodied warriors who fought in the Bronze Age battle.

    The research team analyzed and compared the arrowheads, some of which were still embedded in the remains of the fallen. While many of these weapons were locally produced, some bearing different shapes came from a region that now includes modern Bavaria and Moravia.

    The outliers’ presence suggests that a southern army clashed with local tribes in the valley, and researchers suspect the conflict began at a key landmark along the river.

    Back to the future
    Scientists are harnessing the power of artificial intelligence to detect hidden archaeological sites buried below the sand of the sprawling Rub‘ al-Khali desert.

    The desert spans 250,000 square miles (650,000 square kilometers) on the Arabian Peninsula, and its name translates to “the Empty Quarter” in English. To unravel the secrets of the desolate terrain, researchers are combining machine learning with a satellite imagery technique that uses radio waves to spot objects that may be concealed beneath surfaces.

    The technology will be tested in October when excavations assess whether predicted structures are present at the Saruq Al Hadid complex in Dubai, United Arab Emirates.

    Separately, an AI-assisted analysis uncovered a trove of ancient symbols in Peru’s Nazca Desert, nearly doubling the number of known geoglyphs, or stone and gravel arranged into giant shapes that depict animals, humans and geometric designs.

  28. Профессиональный сервисный центр по ремонту сигвеев в Москве.
    Мы предлагаем: сервис сигвей
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  29. Frankevild表示:

    https://rybelsus.shop/# rybelsus pill

發佈留言

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