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

  1. room decors that are using lead free paints must always be used on our homes “

  2. Trefryo表示:

    Здравствуйте!
    Задумался а действительно можно купить диплом государственного образца в Москве, и был удивлен, все реально и главное официально!
    Сначала серфил в сети и искал такие темы как: купить диплом в рыбинске, купить сертификат специалиста, купить диплом менеджера по туризму, можно ли купить диплом, купить диплом в дзержинске, получил базовую информацию.
    Остановился в итоге на материале купить диплом инженера строителя, https://blogs.rufox.ru/~runoklisfgy/47401.htm
    Удачи!

  3. Next time I read a blog, Hopefully it won’t fail me as much as this one. I mean, Yes, it was my choice to read, however I actually thought you would probably have something useful to talk about. All I hear is a bunch of whining about something you could fix if you were not too busy looking for attention.

  4. Excellent stuff. I can’t describe how much your site has helped me within my academic research on the subject. I’m now likely to get top marks without a doubt. Thanks a thousand. I owe you one.

  5. Excellent! I thank you your contribution to this matter. It has been insightful. my blog: how to get taller

  6. This is the right web site for everyone who really wants to understand this topic. You realize a whole lot its almost tough to argue with you (not that I really will need to…HaHa). You definitely put a fresh spin on a subject which has been written about for many years. Excellent stuff, just great.

  7. Diplomi_ieei表示:

    куплю диплом о среднем специальном образовании ast-diploms.com .

  8. Diplomi_bmet表示:

    диплом 2013 купить diplomyx.com .

  9. Diplomi_acKn表示:

    купить диплом с подтверждением asxdiplomik.com .

  10. Haycrire表示:

    Здравствуйте!
    Для некоторых людей, приобрести диплом о высшем образовании – это острая необходимость, удачный шанс получить выгодную работу. Но для кого-то – это желание не терять время на учебу в институте. С какой бы целью вам это не потребовалось, наша фирма готова помочь. Оперативно, профессионально и недорого сделаем диплом любого года выпуска на государственных бланках со всеми подписями и печатями.
    Наша компания предлагает выгодно заказать диплом, который выполнен на оригинальном бланке и заверен печатями, штампами, подписями официальных лиц. Наш диплом способен пройти любые проверки, даже при использовании профессионального оборудования. Достигайте свои цели быстро и просто с нашей компанией.
    Где купить диплом специалиста?
    http://wow-tour.ru/kupit-diplom-rf-v-moskve-legalnoe-oformlenie-i-garantii
    Успехов в учебе!

  11. Uazraqh表示:

    Привет, друзья!
    Заказать диплом о высшем образовании
    Наша компания предлагает быстро и выгодно приобрести диплом, который выполнен на оригинальной бумаге и заверен печатями, водяными знаками, подписями должностных лиц. Диплом пройдет лубую проверку, даже с применением профессиональных приборов. Достигайте свои цели максимально быстро с нашей компанией.
    Где приобрести диплом специалиста?
    https://micchat.online/read-blog/1623
    Рады оказать помощь!.

  12. kontol表示:

    It’s nearly impossible to find well-informed people about this subject, but you sound like you know what you’re talking about! Thanks

  13. 벼룩시장 구인구직 및 신문 그대로 보기 (PC/모바일) | 구인구직 앱 어플 무료 설치 다운로드 | 모바일 벼룩시장 보는 방법 | 벼룩시장 부동산 | 지역별 벼룩시장 | 벼룩시장 종이신문 에 대해 알아보겠습니다. 섹스카지노사이트

  14. porn表示:

    Hi there! This article could not be written much better! Reading through this article reminds me of my previous roommate! He always kept preaching about this. I most certainly will forward this post to him. Pretty sure he’s going to have a great read. I appreciate you for sharing!

  15. seo 마케팅表示:

    Secret Printed! Discover How Search Engines Rank Websites!
    seo 마케팅

  16. How To Verify Keyword Competition – And Dominate Figure Out!
    백링크 검사

  17. Seo Careers – From Copywriting To Coding – What You Truly Have To Learn 백링크 대행

  18. Lunrlrb表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по приятным тарифам.
    Мы готовы предложить документы техникумов, расположенных на территории всей РФ. Вы имеете возможность приобрести качественный диплом за любой год, указав подходящую специальность и оценки за все дисциплины. Документы печатаются на бумаге самого высокого качества. Это дает возможности делать государственные дипломы, которые невозможно отличить от оригиналов. Они будут заверены необходимыми печатями и подписями.
    Даем 100% гарантию, что при проверке документа работодателем, подозрений не появится.
    Где приобрести диплом по необходимой специальности?
    militarymuster.ca/forum/search.php

  19. Fab表示:

    This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. At Caribbean Stud at Sycuan Casino (San Diego CA), 2 people both almost had straight flushes. The pit said that they would SPLIT 10% of the pot instead of each receiving 10% or the 2nd straight flush receiving 10% after the first straight flush received his 10%. Is that the correct way to pay off? If two people get full houses, they each receive the same amount out of the progressive jackpot so I would like to know what happens when there are two straight flushes. Thank you. Thanks for playing it. Yes, Ties Win Blackjack was a good choice for this promotion. The probability of a full win is 43.314%, a half win is 8.75%, and a loss is 47.936%. So the probability of any win is 52.064%. The probability of five consecutive wins is 0.520645 = 3.825%. Flat betting this results in an extra 3.825% of return for the player. The house edge normally is 0.247%, so the player advantage under this promotion would be 3.5785%. However I find no mention of this promotion on the casino web site and given my usual 2-3 week delay to answer e-mail it is probably over.
    https://e-directory2u.com/listings12740149/poker-chips-for-10-buy-in
    Just sign up for a new DraftKings North Carolina account, deposit $5, and bet $5 on any sport. The $200 in bonus bets are issued as eight (8) $25 bonus bets. Also, note that the bonuses expire in 7 days after being awarded. 88 Free Spins No Deposit Offer Gareth Southgate has announced his provisional squad with a number of surprising additions that will no doubt be discussed extensively as the Three Lions go into Euro 2024 as the favourites Winner Casino is a fully-featured online casino offering fast deposits and withdrawals through banking methods such as VISA, MasterCard, NETeller and Moneybookers. The site also offers free customer support 24 hours per day, 7 days per week through phone and email. Winner Casino includes both downloadable and instant play casino software, allowing users to participate in real money gambling regardless of their operating systems.

  20. Briantes表示:

    Привет!
    Купить диплом ВУЗа.
    Мы предлагаем купить диплом высочайшего качества, который невозможно отличить от оригинального документа без участия специалиста высокой квалификации со сложным оборудованием.
    Где заказать диплом по нужной специальности?
    http://wap.fortboyard2012forum.4adm.ru/viewtopic.php?f=27&t=4120
    Успешной учебы!

  21. This site was… how do I say it? Relevant!! Finally I’ve found something which helped me. Many thanks.

  22. Diplomi_lnmn表示:

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

  23. Tariorzmi表示:

    Привет!
    Где купить диплом по нужной специальности?
    Купить диплом о высшем образовании.
    https://www.gamerlaunch.com/community/users/blog/6452716/2248370/интересное—1067113608/?gid=535
    Рады оказать помощь!

  24. Get A Boost In Traffic To Increase Sales 백링크 검사

  25. Gail表示:

    What Are The Myths And Facts Behind Claim For Asbestos Gail

  26. Hwqerp表示:

    purchase rogaine online cheap – purchase dutas online cheap propecia drug

  27. Binary Options – Legitimate Or Internet Gambling?

    에볼루션 채팅알바

  28. 10 Reasons You Must Be Thinking About Seo 백링크 프로그램

  29. Internet Marketing Tips – How To Advertise A Site 구글 상위노출 백링크

發佈留言

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