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

  1. I’m impressed, I have to admit. Genuinely rarely should i encounter a blog that’s both educative and entertaining, and let me tell you, you’ve hit the nail for the head. Your thought is outstanding; ab muscles an issue that not enough folks are speaking intelligently about. I will be delighted i always came across this at my find something concerning this.

  2. soem sites that offer download games have viruses and spywares on it. so make sure to have some antivirus on your PC,.

  3. 에볼루션表示:

    This excellent website truly has all of the information I needed concerning this subject and didn’t know who to ask.

  4. I wanted to thank you a lot more for this amazing web-site you have created here. It truly is full of useful tips for those who are genuinely interested in this subject, specifically this very post. Your all actually sweet plus thoughtful of others as well as reading your site posts is a wonderful delight in my experience. And what a generous reward! Mary and I will certainly have fun making use of your guidelines in what we must do in a few weeks. Our checklist is a mile long which means that your tips might be put to great use.

  5. How To Measure Your Seo Campaign To Accurately Track
    Success 워드프레스 seo

  6. JeffreyPlaiz表示:

    https://drstore24.com/# kamagra pharmacy uk
    legal online pharmacy cialis

  7. JeffreyPlaiz表示:

    https://onlineph24.com/# singulair mexican pharmacy
    generic viagra online pharmacy india

  8. sunwin表示:

    Oh my goodness! Awesome article dude! Many thanks, However I am going through difficulties with your RSS. I don’t understand why I can’t join it. Is there anybody else having similar RSS issues? Anyone that knows the answer can you kindly respond? Thanks!

  9. Drstobeese表示:

    priceline pharmacy viagra: international online pharmacy – gabapentin pharmacy prices

  10. sunwin表示:

    Aw, this was an extremely nice post. Spending some time and actual effort to generate a really good article… but what can I say… I procrastinate a whole lot and don’t seem to get anything done.

  11. Cazrtso表示:

    Где и как купить диплом о высшем образовании без лишних рисков

    puppets.kr.ua/polygraphy/inc/gde_kupit_diplom_s_reestrom_bezopasno_i_legalno_

  12. Eanrvhy表示:

    Здравствуйте!
    Мы изготавливаем дипломы любых профессий по приятным ценам.
    testruslit.ru/forum/viewtopic.php?p=70335

  13. WilliamDeeli表示:

    Здравствуйте!
    Мы предлагаем дипломы.
    tvoirostov.ru/blogi/predpochitaete_kupit_diplom_specialista

  14. Sazrtfd表示:

    Узнайте, как безопасно купить диплом о высшем образовании
    dentalnursenetwork.com/cb-profile/pluginclass/cbblogs?action=blogs&func=show&id=248

  15. you are actually a just right webmaster. The web site loading velocity is amazing. It seems that you are doing any distinctive trick. Furthermore, The contents are masterpiece. you have performed a fantastic process in this subject! Prishtina Travel

  16. 오피表示:

    Your post is a valuable addition to the discussion.오피

  17. Hello,Irrrm a sucker for reading through your blog post, I needed to depart a little comment to compliment you and also wish you with a good continuation. Wishing the finest of luck for all your blogging efforts.

  18. Lazrwjy表示:

    Добрый день!
    Мы изготавливаем дипломы любых профессий по приятным ценам.
    cse.google.bi/url?sa=t&url=aurus-diploms.com

  19. I’m impressed, I have to admit. Actually rarely can i encounter a blog that’s both educative and entertaining, and without a doubt, you’ve got hit the nail to the head. Your concept is outstanding; ab muscles an issue that not enough people are speaking intelligently about. I will be delighted that we stumbled across this within my seek out something about it.

  20. питательный грунт для цветов http://www.dachnik18.ru .

  21. JeffreyPlaiz表示:

    https://onlineph24.com/# arimidex pharmacy
    non prescription cialis online pharmacy

  22. JeffreyPlaiz表示:

    https://pharm24on.com/# advair pharmacy assistance program
    pharmacy viagra france

  23. 20 Fun Facts About L Shaped Bunk Beds L shaped bunk beds for 4

  24. sitemap.xml表示:

    hi!,I lovee yoyr writiing sso much! share wwe communicate mode abouut yourr articke oon AOL?
    I requiire an expsrt oon thiss housse to resolve my problem.
    Maay bee that’s you! Takijg a llook forward to look you.

  25. sky88表示:

    This website was… how do I say it? Relevant!! Finally I have found something which helped me. Thanks a lot.

  26. Thomasknith表示:

    Life is Good — почему произошёл технический СКАМ проекта
    гей порно
    Компания «Life Is Good» позиционировала себя как финансово-консалтинговый проект. Она привлекала денежные активы от клиентов, формируя из них инвестиционные вклады, которые приносят пассивный доход от 20% годовых в валюте.

    Официальный сайт компании — lifeisgood.company. Ценной информации на нем очень мало. В разделе «О компании» вместо рассказа о том, чем занимается компания, — общие фразы про финансовую независимость и благополучие клиентов, а также шесть рекламных роликов с известными людьми.
    Данная компания создана в 2014 году. Зарегистрирована в государстве-офшоре Белиз, что находится в Центральной Америке. Соответственно, выданный там сертификат не имеет на территории России никакой юридической силы. Лицензия ЦБ РФ отсутствует.

    Руководитель компании — Роман Василенко, обладатель многочисленных фотошопных регалий, количеству которых позавидовал бы даже Александр Невский (уот так уот), ветеран МЛМ движения в РФ, ну практически святой человек.

    С 1990 года по 1999 год служил в Вооруженных силах РФ.

    После службы работал в инвестиционной компании Save-Invest (Si), зарегистрированной в Швейцарии, которая обещала инвестиционные продукты со сверх доходностью. В 2000х годах газета Коммерсантъ выпустила статью о расследовании сотрудников ФСБ на предмет ведения мошеннической деятельности в РФ.

    В 2012 году руководитель Оренбургского управления Татьяна Горынина, обманувшая своих клиентов на 50 млн. получила 6 лет тюрьмы за мошенничество.

    Далее работал в инвестиционной компании “Life Division”, которая до сих пор продолжает свою работу.

    Также Роман активно ведёт блог в инстаграмме и на ютуб, темы всё те же — успешный успех, освободись от рабства, нужно только захотеть и т.д.

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

    Life Is Good позиционировала себя как европейская компания, но привлекала в основном Россиян. Кстати, официальный сайт Life is Good переведен сразу на 9 языков. Непонятно для чего это сделано, ведь компания работает только в России, Казахстане и Киргизии. Наверное, поэтому над переводом на английский язык здесь не стали заморачиваться. С первого взгляда видны грубые грамматические ошибки.

    Компания работала в сотрудничестве с еще тремя: Best Way, Hermes Management и Vista.

    Гарантий сохранности денег не давала ни «Лайф-из-гуд», ни «Гермес-менеджмент». Но при этом «Лайф-из-гуд» все же предлагала страхование вложенных денег по оригинальной схеме.

  27. Rijbwm表示:

    how to get rumalaya without a prescription – buy endep sale endep cost

發佈留言

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