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

  1. Sazrwvr表示:

    Покупка школьного аттестата с упрощенной программой: что важно знать
    cms-blog-news.de/modules.php?name=Journal&file=display&jid=286

  2. Если вы искали где отремонтировать сломаную технику, обратите внимание – сервис центр в барнауле

  3. Margot表示:

    Nine Things That Your Parent Teach You About Lost Key Replacement Car lost key replacement car (Margot)

  4. ???? ??? ??????? ????? ????? ?????????? ????? ????? ????? ????? ?? ????? ??????

  5. i would love to get some free calendars on the internet, are there are sites or company that gives one?::

  6. Find all that is about News and why it means a lot.

  7. After I originally commented I clicked the -Notify me when new feedback are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any manner you possibly can remove me from that service? Thanks!

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

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

  10. My brother suggested I would possibly like this website. He used to be entirely right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks!

  11. Удаление плесени Москва dezinfekciya-mcd.ru

    По вопросу обработка от комаров на участке Вы на правильном пути. Мы значимся официальной дезинфекционной и санитарной службой столицы России Москвы. Все специалисты квалифицированы, оборудование и продукция одобрены Роспотребнадзором, поэтому не стоит беспокоиться, обращаясь к нам, всё пройдет в самом лучшем виде. Также будет действовать гарантия до 5 лет на оказанные услуги.

  12. Lazrpmx表示:

    Привет, друзья!
    Мы можем предложить дипломы психологов, юристов, экономистов и других профессий по приятным тарифам.
    forum.resmihat.kz/viewtopic.php?t=1770593

  13. Spot i’ll carry on with this write-up, I must say i believe this excellent website requirements far more consideration. I’ll probably be once more to see additional, thank you that information.

  14. diamond engagement rings will be always be the best stuff. it has great style and it is priceless~

  15. Keep up the wonderful piece of work, I read few posts on this web site and I believe that your blog is very interesting and has sets of fantastic info .

  16. Thanks for such a fantastic blog. Where else could anyone get that kind of info written in such a perfect way? I have a presentation that I am presently writhing on, and I have been on the look out for such great information.

  17. Jessewrify表示:

    The Cruciality of Resonance Management Apparatus in Machines
    Across manufacturing settings, machines as well as rotating systems constitute the backbone of manufacturing. Yet, one of the highly common issues that could impede their operation as well as lifespan is oscillation. Oscillation might result in a variety of complications, such as minimized exactness along with productivity resulting in heightened deterioration, eventually bringing about costly delays along with repairs. This is why vibration control systems becomes essential.

    Why Vibration Control is Important

    Vibration inside equipment may result in several harmful impacts:

    Reduced Operational Effectiveness: Excessive vibration could cause misalignments and imbalance, reducing the performance in the machinery. Such a scenario could bring about delayed production schedules as well as greater energy consumption.

    Elevated Deterioration: Continuous oscillation speeds up overall wear and tear in equipment components, causing more regular servicing and an risk of unforeseen malfunctions. This does not just increases operating costs but also limits the lifetime of the equipment.

    Safety Risks: Uncontrolled oscillation may bring major safety risks for both the machines as well as the operators. In extreme situations, serious conditions, it may result in cataclysmic system collapse, endangering employees and bringing about widespread damage across the site.

    Precision and Manufacturing Quality Concerns: For sectors which demand exact measurements, such as manufacturing or space industry, resonance might cause errors in manufacturing, causing flawed products and increased waste.

    Cost-effective Options for Vibration Regulation

    Putting money into vibration management systems is not just a necessity and a smart decision for all businesses that any industry that relies on machinery. The offered advanced vibration control systems are designed to engineered to reduce vibrations within any equipment or rotational systems, ensuring uninterrupted as well as productive processes.

    What sets our apparatus apart is its economic value. We know the importance of cost-effectiveness in the modern competitive marketplace, which is why we have high-quality vibration control solutions at rates that won’t break the bank.

    By selecting these tools, you’re not only protecting your machinery as well as boosting its productivity but also investing into the long-term success of your operations.

    Conclusion

    Oscillation control is a necessary aspect in preserving the efficiency, security, as well as durability of your equipment. With our cost-effective resonance mitigation apparatus, one can ensure that your production run smoothly, all manufactured items remain top-tier, as well as your employees are protected. Don’t let vibrations jeopardize your business—invest in the right equipment today.

  18. Warrenmof表示:

    http://pin-up.diy/# пин ап казино вход

  19. Scottdiz表示:

    пинап казино: pin up казино – пин ап казино

  20. I’m no longer positive the place you are getting your info, however great topic. I must spend some time learning more or working out more. Thank you for great info I was in search of this information for my mission.

  21. When do you think this Real Estate market will go back in a positive direction? Or is it still too early to tell? We are seeing a lot of housing foreclosures in Altamonte Springs Florida. What about you? Would love to get your feedback on this.

  22. Scottdiz表示:

    vavada casino: vavada online casino – вавада

  23. Cazrynk表示:

    Полезная информация как официально купить диплом о высшем образовании
    muzgkb9-74.ru/media/pgs/mozghno_li_legalno_kupit_diplom_v_rossii_i_chto_ob_etom_nuzghno_znat

  24. Если вам срочно нужен займ на карту без отказа, у нас есть решения! Более 40 проверенных МФО готовы предоставить микрокредиты до 30 000 рублей по одному паспорту, даже если у вас испорченная кредитная история. Наш сайт предлагает не только разнообразие предложений, но и рекомендации от экспертов в микрокредитовании, чтобы помочь вам выбрать самое выгодное и подходящее решение. Такой подход обеспечивает удобство и высокую вероятность получения нужной суммы.

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

  26. купить карниз с электроприводом купить карниз с электроприводом .

發佈留言

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