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

6,228 Responses

  1. Eanrfoz表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по разумным тарифам.
    followgrown.com/read-blog/2580_ishem-nadezhnyj-magazin-s-attestatami-i-diplomami.html?mode=night

  2. A Preferential Car Loan – Guidelines Of Sport 페르소나 5 얄 다바오 트

  3. Your lawyer will review your employment history to determine if you were exposed to asbestos.
    This will enable them to find companies that manufactured Asbestos Lawyer-containing products that caused your condition.

  4. Great info. Lucky me I ran across your blog by chance (stumbleupon). I’ve saved as a favorite for later.

  5. oscarreys.top表示:

    7 Things About Demo Slot Hades You’ll Kick Yourself For Not Knowing oscarreys.top

  6. 5611432.xyz表示:

    Where Is Key Programming Car One Year From Now?
    5611432.xyz

  7. techchs.biz表示:

    How To Get Approved Funding Modification At Any Bank 청년
    전세 대출, techchs.biz,

  8. hishypesports表示:

    I blog quite often and I really appreciate your information. The article has truly peaked my interest. I’m going to take a note of your website and keep checking for new information about once a week. I opted in for your RSS feed as well.

  9. 15 Shocking Facts About Upvc Door Panels That You Never Knew upvc replacement door locks

  10. Moses表示:

    See What Double Glazing Units Near Me Tricks The Celebs Are Using double glazing units
    near me – Moses

  11. DichaelDax表示:

    I was able to find good advice from your blog posts.
    cratosroyal bet

  12. Sazrbuo表示:

    Здравствуйте!
    Официальная покупка диплома вуза с сокращенной программой в Москве
    tatuheart.ukrbb.net/posting.php?mode=post&f=41&sid=7b3ba5ef4a427c7dadb8d2bc2904d87c
    Рады помочь!.

  13. Diplomi_wlkl表示:

    купить диплом проводника https://diploms-x.com .

  14. Cazrizn表示:

    Привет, друзья!
    Мы готовы предложить документы ВУЗов, расположенных на территории всей России. Вы можете заказать диплом за любой год, указав подходящую специальность и хорошие оценки за все дисциплины. Дипломы и аттестаты делаются на бумаге самого высшего качества. Это позволяет делать государственные дипломы, не отличимые от оригинала. Они будут заверены всеми требуемыми печатями и штампами.
    h374evlkm.blogolenta.com/25164228/%D0%9F%D0%BE%D0%B4%D1%80%D0%BE%D0%B1%D0%BD%D0%BE%D0%B5-%D0%BE%D0%BF%D0%B8%D1%81%D0%B0%D0%BD%D0%B8%D0%B5-%D0%BF%D1%80%D0%B8%D0%BE%D0%B1%D1%80%D0%B5%D1%82%D0%B5%D0%BD%D0%B8%D1%8F-%D0%B0%D1%82%D1%82%D0%B5%D1%81%D1%82%D0%B0%D1%82%D0%B0-%D0%B2-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5

  15. Dnrtskq表示:

    Здравствуйте!
    Купить документ о получении высшего образования вы можете в нашей компании.
    ast-diplomas24.ru/kupit-diplom-o-srednem-obrazovanii
    Успешной учебы!

  16. Xazrrbx表示:

    Здравствуйте!
    Готовы предложить документы техникумов, расположенных в любом регионе РФ. Можно заказать качественно напечатанный диплом от любого учебного заведения, за любой год, включая документы старого образца. Документы печатаются на “правильной” бумаге самого высшего качества. Это дает возможности делать государственные дипломы, которые невозможно отличить от оригиналов. Документы заверяются всеми необходимыми печатями и штампами.
    Мы можем предложить дипломы психологов, юристов, экономистов и других профессий по приятным тарифам. Стоимость зависит от определенной специальности, года выпуска и ВУЗа. Стараемся поддерживать для заказчиков адекватную ценовую политику. Важно, чтобы документы были доступными для большого количества наших граждан.
    landik-diploms-srednee.ru/diplom-bakalavra В 
    Хорошей учебы!

  17. Why Malpractice Settlement Should Be Your Next Big Obsession malpractice lawsuits

  18. Diplomi_zaEa表示:

    Привет!
    Купить документ о получении высшего образования вы имеете возможность у нас в столице.
    ast-diplomas24.ru/kupit-diplom-moskva

  19. Diplomi_yrkl表示:

    купить диплом в питере asxdiplomik24.ru .

  20. Lazrsxr表示:

    Привет!
    Где заказать диплом по нужной специальности?
    Приобрести диплом любого ВУЗа.
    s24.team/club/user/148/blog/1602/

  21. Great article. I am facing some of these issues as well..

  22. Greetings, There’s no doubt that your site may be having browser compatibility issues. Whenever I look at your site in Safari, it looks fine however when opening in I.E., it’s got some overlapping issues. I merely wanted to give you a quick heads up! Other than that, wonderful blog.

  23. Diplomi_lpei表示:

    купить диплом колледжа в краснодаре ast-diploms.com .

  24. iwin68 club表示:

    There is certainly a great deal to find out about this subject. I really like all of the points you’ve made.

  25. Dnrtqxz表示:

    Здравствуйте!
    Заказать документ института вы имеете возможность у нас в столице.
    diplomyx24.ru/kupit-diplom-magistra
    Хорошей учебы!

  26. What’s Everyone Talking About Malpractice Case Today malpractice lawyer

  27. Xazrvwo表示:

    Привет!
    Ьожем предложить документы ВУЗов, расположенных на территории всей Российской Федерации. Можно купить диплом за любой год, указав подходящую специальность и хорошие оценки за все дисциплины. Дипломы и аттестаты печатаются на “правильной” бумаге высшего качества. Это позволяет делать настоящие дипломы, не отличимые от оригинала. Документы заверяются всеми необходимыми печатями и подписями.
    Мы изготавливаем дипломы любой профессии по доступным ценам. Стоимость будет зависеть от выбранной специальности, года получения и образовательного учреждения. Всегда стараемся поддерживать для заказчиков адекватную ценовую политику. Для нас важно, чтобы документы были доступны для большинства наших граждан.
    landik-diploms-srednee.ru/kupit-diplom-v-kazani  
    Удачи!

  28. 5 Killer Quora Answers To Cheap Single Pushchair Single Pushchair

  29. ngentot pepek表示:

    An outstanding share! I’ve just forwarded this onto a coworker who has been conducting a little homework on this. And he actually bought me dinner due to the fact that I found it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanks for spending some time to talk about this issue here on your blog.

發佈留言

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