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

10,388 Responses

  1. JasonUnsoG表示:

    https://casinositeleri25.com/# Canl? Casino Siteleri

  2. 10 Untrue Answers To Common Adult Test For ADHD Questions: Do You Know The Right Ones?

    Adult Testing For Adhd (https://Willysforsale.Com/Author/Yellowage80/)

  3. Wallacefex表示:

    az parayla cok kazandiran slot oyunlar?: slot oyunlar? – slot oyunlar?

  4. FrankEmine表示:

    deneme bonusu veren yeni siteler: deneme bonusu veren siteler yeni – denemebonusuverensiteler25

  5. DavidTouts表示:

    http://casinositeleri25.com/# guvenilir casino siteleri

  6. sát nhân表示:

    Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  7. Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  8. DavidTouts表示:

    https://slotsiteleri25.com/# az parayla cok kazandiran slot oyunlar?

  9. chơi les表示:

    Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  10. Wallacefex表示:

    deneme bonusu veren yeni siteler: yeni deneme bonusu veren siteler – denemebonusuverensiteler25

  11. BradleyEdino表示:

    slot casino siteleri slot oyunlar? puf noktalar? en kazancl? slot oyunlar?

  12. sex trẻ em表示:

    Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  13. FrankEmine表示:

    guvenilir slot siteleri: slot oyunlar? puf noktalar? – slot siteleri

  14. JasonUnsoG表示:

    https://slotsiteleri25.com/# slot oyunlar?

  15. DavidTouts表示:

    https://casinositeleri25.com/# deneme bonusu veren casino siteleri

  16. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт iphone xs адреса, можете посмотреть на сайте: ремонт iphone xs цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. FrankKam表示:

    Biezak uzdotie jautajumi

    Udens spice – ka ta darbojas?
    Udens spice pec butibas ir loti vienkarsa, ta parasti ir polietilena vai metala caurule kura saurbti daudzi mazi caurumi kuriem pa virsu ir ciesi piestiprinats smalks metala vai neilona siets
    spices ierikosana
    Filtracijas siets nodrosina lai caurule ieplust tikai udens, bet pasas smiltis paliek sieta arpuse.
    Udens spice tiek ierikota smilsaina grunti un ierikosanas dzilumu izvelas ta, lai filtracijas siets atrastos pietiekosi dzili zem udens limena, bet pasas smiltis ap filtracijas sietu butu irdenas un udens caurlaidosas.
    Ari dzilums kada sakas gruntsudens ir loti svarigs normalai udens sukna darbibai. Jo dzilak sakas udens limenis, jo udens suknim bus grutak udeni “vilkt” augsa un tadejadi var kristies udens raziba.

    Vai spici var ierikot jebkura vieta?
    Ka jau ieprieks teksta minets – ir loti svarigi, lai vieta, kur velaties ierikot spici, butu “atbilstosas” smiltis udens spices ierikosanai. Ja smilts ir graudaina (irdena) un gruntsudens limenis nesakas dzilak par 6m no zemes virsmas, tad spici ierikot nevajadzetu but nekadam problemam. Ja smiltis nav parak liels mala piejaukums, … Lasit vairak

    Vai var ticet aderem?
    Aderu meklesana tiesi ziemelu tautas valstis ir loti izplatits veids ka “atrast udeni” un paaudzu paaudzes so amatu pielieto vietejie aku raksanas meistari un reizem pat spices ierikosanas meistari apgalvojot ka spej “paredzet” udens atrasanas vietu un dzilumu jeb ta saucamas “pazemes upes”. Ari Latvija netrukst cilveku, kas tic sadam … Lasit vairak

    Spices ierikosana vai dzilurbums – kadas ir atskiribas?
    Spices ierikosanai, vispirms tas ir Diametrs – Polietilena spicem visizplatitakais diametrs ir 32mm un metala spicem – 40mm (jeb 1 ?”). Udens spici apriko ar virszeme novietojamu udens sukni, jeb ta tauta deveto “hidroforu”. Savukart dzilurbuma diametrs ir sakot no 80mm. Pateicoties lielakam caurules diametram, taja var ievietot iegremdejamo sukni … Lasit vairak

    Polietilena spices un metala spices – ar ko tas atskiras?
    Polietilena spices ir samera moderns risinajums un tas pirmo reizi Latvija paradijas aptuveni pirms 25 gadiem. To kimiska izturiba ir pielidzinama nerusejosam teraudam – tas neruse, neoksidejas un visa garuma nav nevienas savienojuma vietas, kas padara gaisa piesuksanu caur “izpuvusiem” un valigiem savienojumiem neiespejamu, ka ari krietni atvieglo montazu. Virsu … Lasit vairak

    Spices ierikosana ir jasaskano buvvalde?
    Spices ierikosana lidz 20 metru dzilumam nav jasaskano buvvalde un par to nav jamaksa “zemes dzilu resursu izmantosanas nodoklis”. Ari spices atrasanas vieta ir pec jusu izveles – to var ierikot pie kaiminu zoga cik vien tuvu velaties, tas var ierikot ieksa telpa, pagraba vai tuvu pamatiem. Udens spices nekadi … Lasit vairak

    Spices udens kvalitate.
    Spices udens kvalitate ir biezi apspriests temats. Var skist, ka udens no dzilurbuma vienmer bus tiraks un labaks neka no spices un lai iegutu labako udeni ir jaurbj pec iespejas dzilak, bet ne vienmer ta ir. Reizem Riga un Rigas rajona tiesi no samera seklam spicem (lidz 10m dzilumam, kas … Lasit vairak

  18. Wallacefex表示:

    en cok kazand?ran slot oyunlar?: az parayla cok kazandiran slot oyunlar? – slot siteleri

  19. BradleyEdino表示:

    casino bahis siteleri casino bahis siteleri deneme bonusu veren casino siteleri

  20. DavidTouts表示:

    http://denemebonusuverensiteler25.com/# deneme bonusu veren siteler yeni

  21. Helena表示:

    The Most Effective Cleaning Robot Mop And Vacuum
    Tips To Transform Your Life robot vacuum – Helena

  22. FrankEmine表示:

    denemebonusuverensiteler25: denemebonusuverensiteler25 – deneme bonusu veren siteler

  23. ebgcknsub表示:

    Football fans often spend Saturday morning studying the English Championship betting tips ahead of the afternoon fixtures, with 12 matches taking place over the course of a weekend. Josh Dacres-Cogley is an eye-catching arrival from Tranmere and we’ve also seen Joel Coleman, Nathan Baxter, Dan Nlundulu and Will Forrester sign for an ambitious club who could well seal automatic this time around. If you are looking for other ideas for betting check out our football accumulator tips page. Don’t forget to take a look at the form curves of both teams to find the tendency you have just identified. So do the previously analysed and identified statements still apply in the most recent three to five matches? Or were precisely these matches finished with a particularly high number of goals – which would tend to argue against an under bet? And how do things look exclusively in the home and away matches of the Schalkers and Dortmunders? So you see: Goal bets for your betting tips today & tomorrow are a perfect alternative with many variants whenever no clear favourite can be identified in a pairing. In addition, you can play with the risk you are willing to take in your bets. Here are a few more tips.
    https://urlscan.io/result/84164221-8562-40d5-8dbe-4359013ae389/loading
    There are many sites that purport to predict football matches correctly. So, which one should you trust? Which site is the best football prediction website?One site that has a good reputation for accurately offering soccer predictions and tips is kingspredict. This site uses a complex algorithm to make its predictions, taking into account a variety of factors, such as home-field advantage, soccer team picks, recent results, and injuries. You can contact us here for more information. Switzerland – Challenge League You must be 18 years old or over to use this website. Gamble Responsibly. Sports experts have posted all of the most recent FREE betting predictions for today, tomorrow, and the weekend. A GG BTTS prediction is a type of soccer bet that involves predicting whether both teams will score or not. It doesn’t matter which team wins or loses the game. All that matters is whether both teams score at least one goal each or not.

  24. Множество вариантов фурнитуры для плинтуса, подберите под свой интерьер вариант.
    Качественная фурнитура для плинтуса, не подведут вас в эксплуатации.
    Простота установки элементов плинтуса, без лишних усилий.
    Современные решения для отделки плинтуса, подчеркните стиль своего интерьера.
    Фурнитура для плинтуса из экологически чистых материалов, сделайте свой дом более безопасным для здоровья.
    Тренды в оттенках для декора плинтуса, создайте гармонию в доме.
    Уникальные элементы для стильного плинтуса, выразите свою индивидуальность через дизайн.
    Подсказки по правильной установке элементов плинтуса, для долгосрочного использования.
    Креативные решения для отделки плинтуса, выдержите общий стиль в каждой детали.
    Элегантные элементы для стильного плинтуса, подчеркните изысканный вкус в дизайне.
    напольные покрытия https://furnituradlyaplintusamsk.ru/ .

  25. JasonUnsoG表示:

    http://slotsiteleri25.com/# en kazancl? slot oyunlar?

  26. Wallacefex表示:

    sweet bonanza yorumlar: sweet bonanza giris – sweet bonanza demo oyna

  27. DavidTouts表示:

    https://denemebonusuverensiteler25.com/# yeni deneme bonusu veren siteler

  28. DavidTouts表示:

    http://slotsiteleri25.com/# guvenilir slot siteleri

  29. 5 Killer Quora Answers On Asbestos Mesothelioma Lawyers Mesothelioma Lawyer

發佈留言

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