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

2,945 Responses

  1. Ronaldpsymn表示:

    http://lisinopril.network/# url lisinopril hctz prescription

  2. RandallTaulp表示:

    buy cipro online: cipro ciprofloxacin – cipro for sale

  3. Timsothyabela表示:

    В нашем обществе, где диплом – это начало отличной карьеры в любом направлении, многие стараются найти максимально быстрый и простой путь получения качественного образования. Наличие официального документа переоценить просто невозможно. Ведь диплом открывает двери перед людьми, стремящимися начать трудовую деятельность или учиться в ВУЗе.
    Наша компания предлагает быстро получить любой необходимый документ. Вы сможете купить диплом нового или старого образца, и это будет удачным решением для всех, кто не смог завершить образование, утратил документ или желает исправить плохие оценки. диплом изготавливается с особой тщательностью, вниманием ко всем нюансам. На выходе вы получите 100% оригинальный документ.
    Превосходство данного решения заключается не только в том, что можно оперативно получить свой диплом. Процесс организовывается удобно, с профессиональной поддержкой. Начав от выбора необходимого образца диплома до консультаций по заполнению персональных данных и доставки в любое место страны — все под полным контролем качественных мастеров.
    В итоге, для тех, кто ищет оперативный способ получения необходимого документа, наша услуга предлагает выгодное решение. Купить диплом – это значит избежать продолжительного обучения и не теряя времени переходить к достижению своих целей, будь то поступление в университет или начало карьеры.

    https://diploman-russiyan.com

  4. RandallTaulp表示:

    liquid tamoxifen: tamoxifen hair loss – tamoxifen and osteoporosis

  5. WilliamRhype表示:

    http://nolvadex.life/# tamoxifen breast cancer

  6. WilliamRhype表示:

    https://cytotec.club/# order cytotec online

  7. Ronaldpsymn表示:

    http://nolvadex.life/# tamoxifen for gynecomastia reviews

  8. WilliamRhype表示:

    http://finasteride.store/# cost of propecia tablets

  9. Davidtes表示:

    zestoretic cost zestril tab 10mg price of lisinopril 5mg

  10. OLaneevige表示:

    В современном мире, где диплом является началом отличной карьеры в любом направлении, многие пытаются найти максимально быстрый путь получения качественного образования. Наличие официального документа об образовании переоценить попросту невозможно. Ведь диплом открывает двери перед всеми, кто стремится вступить в сообщество профессионалов или учиться в университете.
    В данном контексте наша компания предлагает максимально быстро получить этот важный документ. Вы можете приобрести диплом нового или старого образца, и это становится отличным решением для человека, который не смог завершить образование или утратил документ. диплом изготавливается аккуратно, с особым вниманием к мельчайшим деталям, чтобы на выходе получился документ, 100% соответствующий оригиналу.
    Плюсы подобного решения заключаются не только в том, что можно оперативно получить свой диплом. Весь процесс организовывается комфортно и легко, с нашей поддержкой. От выбора подходящего образца до консультации по заполнению личной информации и доставки в любой регион России — все под полным контролем качественных мастеров.
    В итоге, всем, кто пытается найти быстрый и простой способ получения требуемого документа, наша компания готова предложить выгодное решение. Купить диплом – значит избежать долгого обучения и сразу переходить к своим целям, будь то поступление в университет или начало успешной карьеры.

    https://diploman-rossiya.com

  11. Davidtes表示:

    propecia cheap cost of cheap propecia without rx cost propecia no prescription

  12. Davidtes表示:

    propecia generic cheap propecia no prescription cost generic propecia without prescription

  13. RandallTaulp表示:

    buy propecia now: buying generic propecia no prescription – buying propecia price

  14. RandallTaulp表示:

    buy cytotec online: buy cytotec online fast delivery – buy cytotec pills

  15. RandallTaulp表示:

    cipro online no prescription in the usa: buy cipro – buy ciprofloxacin

  16. WilliamRhype表示:

    https://ciprofloxacin.tech/# cipro pharmacy

  17. WilliamRhype表示:

    http://cytotec.club/# Cytotec 200mcg price

  18. Davidtes表示:

    tamoxifen side effects forum tamoxifen hormone therapy raloxifene vs tamoxifen

  19. Davidtes表示:

    lisinopril online usa lisinopril generic price comparison buy lisinopril online no prescription

  20. Davidtes表示:

    cytotec online п»їcytotec pills online buy cytotec pills

  21. OLaneevige表示:

    На сегодняшний день, когда диплом – это начало удачной карьеры в любом направлении, многие ищут максимально быстрый путь получения образования. Необходимость наличия официального документа трудно переоценить. Ведь диплом открывает дверь перед каждым человеком, который собирается начать трудовую деятельность или продолжить обучение в каком-либо ВУЗе.
    Мы предлагаем оперативно получить этот необходимый документ. Вы сможете заказать диплом, и это становится удачным решением для всех, кто не смог завершить образование или потерял документ. Каждый диплом изготавливается аккуратно, с максимальным вниманием к мельчайшим нюансам, чтобы на выходе получился полностью оригинальный документ.
    Преимущество такого подхода состоит не только в том, что можно оперативно получить свой диплом. Процесс организовывается комфортно и легко, с нашей поддержкой. От выбора требуемого образца до консультаций по заполнению персональных данных и доставки в любое место России — все находится под абсолютным контролем наших специалистов.
    Для тех, кто пытается найти быстрый способ получить необходимый документ, наша компания готова предложить выгодное решение. Заказать диплом – значит избежать продолжительного обучения и сразу переходить к своим целям, будь то поступление в университет или начало карьеры.

    https://diploman-russiyan.com

  22. WilliamRhype表示:

    http://nolvadex.life/# tamoxifen citrate

  23. Ronaldpsymn表示:

    http://lisinopril.network/# best lisinopril brand

  24. RandallTaulp表示:

    lisinopril 60 mg tablet: medication lisinopril 5 mg – lisinopril 20 mg india

  25. Ronaldpsymn表示:

    http://nolvadex.life/# tamoxifen alternatives premenopausal

  26. RandallTaulp表示:

    tamoxifen: tamoxifen – low dose tamoxifen

  27. WilliamRhype表示:

    https://nolvadex.life/# nolvadex only pct

  28. RandallTaulp表示:

    Cytotec 200mcg price: order cytotec online – buy cytotec over the counter

  29. Davidtes表示:

    buy ciprofloxacin over the counter where can i buy cipro online ciprofloxacin over the counter

  30. Davidtes表示:

    buy ciprofloxacin over the counter ciprofloxacin mail online cipro online no prescription in the usa

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

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