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

7,875 Responses

  1. Cecilia表示:

    Shop Online Google Pay Tools To Ease Your Daily Lifethe
    One Shop Online Google Pay Trick That Every Person Should Know shop online
    google pay; Cecilia,

  2. Reent表示:

    1) We couldn’t find this job! Incumbent will conduct the majority of work at the Department of Technology, One South Van Ness Avenue, 2nd Floor.  However, there may be situations where the incumbent will be required to work at other sites throughout the City of San Francisco as necessary. The department is currently working in a hybrid model; however, telecommuting options are available upon the appointing officer’s approval and at the appointing officer’s discretion. Confidential,July 2009 to January 2011 Desktop Support Specialist (Contractor) On-site in Knoxville, Tennessee, USA Qualifications for a job description may include education, certification, and experience. Information technology (IT) is one of the fastest-growing fields and it’s projected that there will be over 667,600 new jobs in the industry by 2030. As technology continues to advance at a break-neck speed, skilled IT professionals will be in more demand than ever. That means there’s no better time than now to take the first steps toward training for an entry-level IT job. Here are four reasons to become an IT support specialist today.
    https://direct-wiki.win/index.php?title=It_project_planning
    Hopefully, this article helped! Please let me know which method helped you, or if you have a better idea on how to fix this issue. I would love your thoughts! In these instances, the computer should otherwise appear to run well. Diagnosis should be easy to reproduce. Simply launch the program for a game or media player, and view in full screen mode. RizTech is proud to offer you superior customer service, the most recommended repair service in NE Ohio with FREE diagnostics and friendly attention to detail all backed with a warranty, savings as EVERYTHING at RizTech is priced below MSRP and we feature NE Ohio’s largest selection of new and refurbished computers to fit any need and every budget.  Need a laptop screen repair or laptop screen replacement? Signs you may need a replacement screen for laptop include:

  3. Nelsonbluck表示:

    п»їbest mexican online pharmacies: mexican border pharmacies shipping to usa – medication from mexico pharmacy

  4. Danrrks表示:

    Добрый день!
    Мы предлагаем дипломы любой профессии.
    datasheetclub.com/read-blog/85_nadezhnyj-i-proverennyj-onlajn-magazin-s-ogromnym-vyborom-dokumentov
    Всегда вам поможем!.

  5. Hey, – Gulvafslibning | Kurt Gulvmand is a tremendously helpful post! Funny, I came over just to make sure I hadn’t missed anything and I come across a really worthwhile post

  6. Arnoldten表示:

    pharmacies in mexico that ship to usa mexican rx online purple pharmacy mexico price list

  7. could allow go of somebody I cherished, to take on wild adventures I’d certainly not get to get in serious lifetime, to get nightly vacations in the course

  8. tubidy mp3表示:

    Good post. I learn something totally new and challenging on websites I stumbleupon every day. It will always be helpful to read content from other authors and practice a little something from their web sites.

  9. Some genuinely great blog posts on this internet site , regards for contribution.

  10. Mazrvva表示:

    Здравствуйте!
    Полезные советы по покупке диплома о высшем образовании без риска
    mandiplomik.ru

  11. WayneCoirl表示:

    pharmacies in mexico that ship to usa: purple pharmacy mexico price list – medicine in mexico pharmacies

  12. DominicJaw表示:

    medicine in mexico pharmacies: mexico drug stores pharmacies – mexican border pharmacies shipping to usa

  13. Dnrteae表示:

    Здравствуйте!
    Приобрести документ о получении высшего образования вы имеете возможность в нашей компании в Москве.
    ast-diplom.com/kupit-diplom-nizhnij-novgorod
    Успешной учебы!

  14. Lazrngv表示:

    Здравствуйте!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    newsato.ru/kupit-diplom-garantiya-kachestva-i-bezopasnosti

  15. Nelsonbluck表示:

    purple pharmacy mexico price list: medicine in mexico pharmacies – mexico drug stores pharmacies

  16. Diplomi_qnEa表示:

    Здравствуйте!
    Купить документ о получении высшего образования вы можете у нас.
    ast-diploms.com/kupit-diplom-perm

  17. Arnoldten表示:

    mexican mail order pharmacies buying from online mexican pharmacy buying prescription drugs in mexico

  18. RichardWrifs表示:

    https://mexicandeliverypharma.com/# buying prescription drugs in mexico online

  19. WayneCoirl表示:

    п»їbest mexican online pharmacies: medicine in mexico pharmacies – mexican pharmaceuticals online

  20. DominicJaw表示:

    mexican pharmaceuticals online: best online pharmacies in mexico – purple pharmacy mexico price list

  21. Hello there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  22. Recently, I didnt give lots of thought to leaving comments on site page articles and have placed comments even much less. Reading by means of your nice article, will help me to do so sometimes.

  23. Pretty! This has been a really wonderful article. Thank you for providing these details.

  24. Cool blog. Maybe i can help you in writing fresh content, are you interested ?

  25. Arnoldten表示:

    buying prescription drugs in mexico mexican mail order pharmacies mexican pharmacy

  26. Your website does not show up correctly on my apple iphone – you might want to try and fix that

  27. Reese Witherspoon have the most beautiful eyes among american actresses, i just can’t get enough of her beautiful eyes`

  28. RichardWrifs表示:

    http://mexicandeliverypharma.com/# purple pharmacy mexico price list

發佈留言

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