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. Hermanswoff表示:

    online shopping pharmacy india: Online medicine order – pharmacy website india

  2. Mazrfzk表示:

    Здравствуйте!
    Как правильно купить диплом колледжа и пту в России, подводные камни
    images.google.com.gh/url?sa=t&url=aurus-diploms.com

  3. JeremyPsymn表示:

    https://easyrxindia.shop/# indian pharmacy

  4. Trefegw表示:

    Привет, друзья!
    Приобретение диплома ПТУ с сокращенной программой обучения в Москве
    filmchik.3dn.ru/forum/5-41-1#3612
    Рады оказать помощь!.

  5. AnthonyPress表示:

    cheap canadian pharmacy canadian pharmacy 24 com northern pharmacy canada

  6. porn表示:

    You are so interesting! I don’t suppose I’ve read through anything like that before. So good to discover someone with unique thoughts on this subject matter. Seriously.. thank you for starting this up. This site is one thing that is required on the internet, someone with some originality.

  7. TK88表示:

    Great site you have here.. It’s hard to find excellent writing like yours nowadays. I really appreciate individuals like you! Take care!!

  8. AnthonyPress表示:

    п»їbest mexican online pharmacies buying from online mexican pharmacy medication from mexico pharmacy

  9. Eanriir表示:

    Привет!
    Мы изготавливаем дипломы любых профессий по приятным тарифам.
    ba98.org/contact.php?sujet=6

  10. Greetings! Very useful advice within this post! It is the little changes which will make the most significant changes. Many thanks for sharing!

  11. WilliamDeeli表示:

    Привет, друзья!
    Мы изготавливаем дипломы.
    re-port.ru/users/50423

  12. Diplomi_vhEa表示:

    Здравствуйте!
    Купить документ о получении высшего образования можно у нас.
    advertmaking.ru/o-skripte/1-post1

  13. Peterhew表示:

    safe reliable canadian pharmacy: online pharmacy canada – pharmacy com canada

  14. I need to to thank you for this wonderful read!! I definitely loved every little bit of it. I have you book marked to look at new things you post…

  15. Robertengep表示:

    https://easyrxindia.com/# buy medicines online in india

  16. Robertengep表示:

    https://mexstarpharma.com/# mexico drug stores pharmacies

  17. Dnrtzxo表示:

    Добрый день!
    Купить документ о получении высшего образования можно в нашем сервисе.
    1wum.ru/forum/?PAGE_NAME=profile_view&UID=37175&MUL_MODE=

  18. Eugeneaftek表示:

    Tiny shards of plastic are increasingly infiltrating our brains, study says
    гей порно геей
    Human brain samples collected at autopsy in early 2024 contained more tiny shards of plastic than samples collected eight years prior, according to a preprint posted online in May. A preprint is a study which has not yet been peer-reviewed and published in a journal.

    “The concentrations we saw in the brain tissue of normal individuals, who had an average age of around 45 or 50 years old, were 4,800 micrograms per gram, or 0.5% by weight,” said lead study author Matthew Campen, a regents’ professor of pharmaceutical sciences at the University of New Mexico in Albuquerque.
    “Compared to autopsy brain samples from 2016, that’s about 50% higher,” Campen said. “That would mean that our brains today are 99.5% brain and the rest is plastic.”

    That increase, however, only shows exposure and does not provide information about brain damage, said Phoebe Stapleton, an associate professor of pharmacology and toxicology at Rutgers University in Piscataway, New Jersey, who was not involved in the preprint.

    “It is unclear if, in life, these particles are fluid, entering and leaving the brain, or if they collect in neurological tissues and promote disease,” she said in an email. “Further research is needed to understand how the particles may be interacting with the cells and if this has a toxicological consequence.”

    The brain samples contained 7% to 30% more tiny shards of plastic than samples from the cadavers’ kidneys and liver, according to the preprint.

    “Studies have found these plastics in the human heart, the great blood vessels, the lungs, the liver, the testes, the gastrointestinal tract and the placenta,” said pediatrician and biology professor Dr. Philip Landrigan, director of the Program for Global Public Health and the Common Good and the Global Observatory on Planetary Health at Boston College.

    “It’s important not to scare the hell out of people, because the science in this space is still evolving, and nobody in the year 2024 is going to live without plastic,” said Landrigan, who was not involved with the preprint.

  19. AnthonyPress表示:

    indian pharmacies safe indian pharmacy world pharmacy india

  20. AnthonyPress表示:

    mexico drug stores pharmacies mexico pharmacies prescription drugs mexican mail order pharmacies

  21. Sazrryg表示:

    Привет, друзья!
    Диплом экономиста
    telegra.ph/kupit-diplom-kosmetologa-ehstetista-08-22

  22. JeremyPsymn表示:

    http://easyrxcanada.com/# canadian pharmacy ratings

  23. Tpower Casino表示:

    Aw, this was an incredibly good post. Finding the time and actual effort to create a superb article… but what can I say… I put things off a whole lot and never manage to get anything done.

  24. Mazrwdj表示:

    Добрый день!
    Как быстро получить диплом магистра? Легальные способы
    intensedebate.com/people/danilowwitek

  25. Sazrfoa表示:

    Привет!
    Диплом для вас
    forum.artinvestment.ru/member.php?u=1807451

  26. Cazrtwe表示:

    Добрый день!
    Приобрести диплом ВУЗа
    rf-4fun.ru/index.php?/topic/1865-нерф-кор/#comment-3554

  27. Hermanswoff表示:

    indian pharmacy online: reputable indian pharmacies – Online medicine home delivery

  28. Hermanswoff表示:

    online pharmacy india: online pharmacy india – top online pharmacy india

發佈留言

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