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

  1. Robertleare表示:

    Opening a bank account in Singapore for a foreigner is a relatively simple and affordable procedure that can be done as long as all banking requirements are met. Due to its openness and attractiveness to foreign investors, Singapore offers unique opportunities for international financial transactions and asset management.
    Financial forecasts
    Developing and implementing an effective marketing strategy is critical to the success of a forex company. Include SEO, contextual advertising, social media and direct marketing activities in your plan.
    Examples of the circumstances when your crypto company requires a license:
    COMPANY FORMATION IN LITHUANIA

    Belize, as a jurisdiction with an emerging gambling market, attracts investors with its favourable business environment. Obtaining a gambling licence here is becoming a strategic decision for companies seeking to expand their international presence. This article discusses the key aspects of the process of obtaining a gambling licence in Belize, including timelines and requirements.
    Should a company in Ireland have employees?
    A list of the directors and secretary of the foreign company, as well as an indication of the persons authorized to act on behalf of the Malta branch.
    Selecting a bank
    Choosing the legal form of the business: It can be a sole proprietorship, partnership or corporation.

  2. cbd oil表示:

    You ought to be a part of a contest for one of the highest quality websites on the internet. I’m going to recommend this web site!

  3. Lazrspz表示:

    Добрый день!
    Мы изготавливаем дипломы любой профессии по приятным тарифам.
    itogi-progressa.ru/2113-lechenie-kisty-zuba

  4. самые точные прогнозы на спорт http://www.rejting-kapperov13.ru/ .

  5. Xazrupr表示:

    Привет!
    Купить документ ВУЗа.
    Мы можем предложить дипломы любой профессии по доступным ценам.
    tdgoodwin.ru
    Будем рады вам помочь!.

  6. Diplomi_ceEa表示:

    Здравствуйте!
    Приобрести документ о получении высшего образования вы можете в нашей компании в Москве.
    transurfing-real.ru/2017/12/blog-post_401

  7. Профессиональный сервисный центр по ремонту ноутбуков, imac и другой компьютерной техники.
    Мы предлагаем:ремонт аймак в москве на дому
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  8. Trefcqr表示:

    Здравствуйте!
    Официальная покупка диплома вуза с упрощенной программой обучения
    sehrnetta.blogspot.com/2010/05/blog-post_18
    Поможем вам всегда!.

  9. Mazraie表示:

    Здравствуйте!
    Как официально купить аттестат 11 класса с упрощенным обучением в Москве
    lhotkanet.cz/galerie/profile.php?uid=75791

  10. Keithexeld表示:

    The ghost town that has stood empty for more than a century
    после анального секса
    There’s a large and very dignified school in Kayakoy. There are narrow streets, lined with houses, that wend and rise up both sides of a steep valley. There’s an ancient fountain in the middle of the town. And there are churches, one with million-dollar hilltop views over the blue Aegean.

    But, for most of the past 100 years, there have been no people.

    Kayakoy, in southwestern Turkey’s Mugla Province, is a true ghost town. Abandoned by its occupants and haunted by the past. It’s a monument, frozen in time – a physical reminder of darker times in Turkey.

    With hillsides dotted by countless crumbling buildings slowly being swallowed by greenery, and endless views into vanished lives, it’s also a fascinating and starkly beautiful place to visit. In summer, under clear skies and blazing suns, it’s eerie enough. Even more so in cooler seasons, wreathed in mountain or sea mists.
    Just over a century ago, Kayakoy, or Levissi as it was known, was a bustling town of at least 10,000 Greek Orthodox Christians, many of whom were craftspeople who lived peacefully alongside the region’s Muslim Turkish farmers. But in the upheaval surrounding Turkey’s emergence as an independent republic, their simple lives were torn apart.

    Tensions with neighboring Greece after the Greco-Turk war ended in 1922 led to both countries ejecting people with ties to the other. For Kayakoy, that meant a forced population exchange with Muslim Turks living in Kavala, in what is now the Greek region of Macedonia and Thrace.

    But the newly arrived Muslims were reputedly less than happy with their new home, swiftly moving on and leaving Kayakoy to fall to ruin.

  11. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: ремонт телефонов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  12. Way cool! Some very valid points! I appreciate you writing this post and also the rest of the website is extremely good.

  13. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: мастерская телефонов рядом
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: номер телефона ремонта телефонов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. After I initially commented I appear to have clicked the -Notify me when new comments are added- checkbox and from now on every time a comment is added I get 4 emails with the same comment. Perhaps there is a means you can remove me from that service? Appreciate it.

  16. Lazrizi表示:

    Здравствуйте!
    Мы предлагаем дипломы любых профессий по выгодным тарифам.
    dpou.info/index.php?page=1337351387&nom_page=1&

  17. Trefppm表示:

    Привет!
    Стоимость дипломов высшего и среднего образования и как избежать подделок
    sweetburg.ru/course/paket-reczepturnyh-kart-na-mussovye-torty-koktejlnaya-vecherinka/#comment-5725
    Поможем вам всегда!.

  18. Sazrhlm表示:

    Привет!
    Диплом любой специальности
    telegra.ph/diplom-fitnes-trenera-kupit-08-13-5

  19. JoshuaDen表示:

    The man turning jet planes into cool houses
    смотреть порно жесток
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  20. Eanrysg表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по приятным тарифам.
    iawbs.com/home.php?mod=space&uid=792962&do=profile&from=space

  21. Frankguara表示:

    The man turning jet planes into cool houses
    гей порно молодые
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  22. WilliamDeeli表示:

    Привет!
    Мы предлагаем дипломы.
    forum.nedug.ru/blog.php?cp=16304

  23. Richardsudge表示:

    The man turning jet planes into cool houses
    гей порно видео
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  24. Diplomi_yyEa表示:

    Добрый день!
    Заказать документ университета можно в нашем сервисе.
    suitsandsuitsblog.com/writer/2019/02/28/20190315-3/#comment-387983

發佈留言

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