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

15,774 Responses

  1. Jasonzitte表示:

    The ambiance of the pharmacy is calming and pleasant.
    can i get clomid without a prescription
    A cornerstone of our community.

  2. Victorprima表示:

    Their patient education resources are top-tier.
    order generic cipro prices
    Been a loyal customer for years and they’ve never let me down.

  3. Victorprima表示:

    They bridge the gap between countries with their service.
    can i order cheap lisinopril pills
    Their worldwide pharmacists’ consultations are invaluable.

  4. Jasonzitte表示:

    The staff always remembers my name; it feels personal.
    where can i get cheap clomid prices
    Outstanding service, no matter where you’re located.

  5. The 10 Scariest Things About Best Robot Vacuums Uk robot vacuums
    uk (ezproxy.cityu.edu.hk)

  6. Jasonzitte表示:

    The staff exudes professionalism and care.
    how long until gabapentin is out of your system
    Been a loyal customer for years and they’ve never let me down.

  7. See What Baby African Grey Parrot For Sale Tricks The Celebs Are Using baby african grey parrot For Sale

  8. Victorprima表示:

    I always feel valued and heard at this pharmacy.
    can you mix gabapentin and suboxone
    Speedy service with a smile!

  9. Victorprima表示:

    They have an extensive range of skincare products.
    buy cheap cipro no prescription
    Read here.

  10. Jeannine表示:

    This Is The Advanced Guide To Item Upgrade item level upgrade – Jeannine,

  11. Georgeappox表示:

    Hidden World War II tunnels to open to public
    юристы Запорожье

    In this week’s roundup of travel news: Denver’s weed church, zodiac predictions for the Year of the Snake, plus what promises to be London’s most ambitious – and deepest – new visitor attraction.

    Going underground
    Some 30 meters (98 feet) below central London lies a mile-long network of tunnels that is set to be the UK capital’s glitziest new tourist attraction, according to the company that’s secured planning approval for the $149 million transformation.

    The Kingsway Exchange Tunnels were built in the 1940s to shelter Londoners from the Blitz bombing campaign during World War II. That was the last time they were open to the general public. Their next wartime role was as the home of Britain’s top-secret Special Operations Executive, an offshoot of MI6 and the real-life inspiration for James Bond’s Q Branch.

    The new attraction will be a memorial to the Blitz, which Angus Murray, chief executive of the London Tunnels, told Reuters will be part museum, part exhibition and part entertainment space.

    The plan is to open to the public by late 2027 or early 2028. Read more here in our earlier story announcing the project.

    If you can’t wait until then to get down in the city’s bowels, London Transport Museum runs exclusive guided tours of its abandoned tube stations, including Down Street, a secret underground bunker that helped win World War II.
    Year of the Snake
    The first new moon of the lunar calendar fell on January 29, ushering in the Year of the Snake and the 15-day Spring Festival, a big annual highlight in China and for Chinese communities around the world.

    Here’s our guide to what it all means and, whether you’re a horse, goat, monkey, rooster or any other sign in the Chinese zodiac, here’s what the stars say are your predictions for the year ahead.

    Food is, of course, a key part of the celebrations. One of the most fun elements is the “prosperity toss,” kind of like a food fight with chopsticks but seasoned with auspicious blessings for the year ahead.

    For the culinarily adventurous, 2025 is a good time to visit Hong Kong and see how restaurants serve snake. Delights include snake balls and snake soup – and be sure to leave room for the penis wine. Watch here.

  12. Jasonzitte表示:

    The pharmacists always take the time to answer my questions.
    order cheap cipro no prescription
    Their global approach ensures unparalleled care.

  13. Jasonzitte表示:

    They have an impressive roster of international certifications.
    can i buy cytotec tablets
    Impressed with their wide range of international medications.

  14. 10 Things You Learned In Kindergarden That Will Help You Get Pragmatic
    Free Trial 프라그마틱 홈페이지

  15. Jorgeham表示:

    ак заказать продвижение сайта и понять цену?
    В прошлом посте мы рассказали, почему продвижение сайта в топ Yandex важно для вашего бизнеса. Сегодня разберём, как заказать продвижение сайта у SMM Portable и что влияет на цену услуги. Этот пост поможет вам освоить процесс и выбрать лучший план для раскрутки сайта.
    Как заказать SEO-услуги?
    Процесс заказа прост и включает три шага:
    Связаться с нами: Напишите нам в Telegram или заполните форму на сайте SMM Portable.
    seo продвижение сайтов от 130000 р
    Предоставить информацию: Укажите URL сайта, целевые запросы (например, “купить мебель в Москве”) и цели бизнеса.

    Консультация и анализ: Мы проведём аудит вашего сайта, оценим конкурентов и предложим стратегию продвижения.
    После этого мы берём всё в свои руки, чтобы ваш сайт начал привлекать больше клиентов.
    Как формируется цена?
    Стоимость SEO зависит от нескольких факторов:
    Уровень конкуренции: Высококонкурентные ниши (например, недвижимость) требуют больше ресурсов.

    Состояние сайта: Новый сайт или сайт с ошибками нуждается в дополнительной оптимизации.

    Ключевые запросы: Продвижение по популярным словам дороже, чем по узким запросам.
    Примерные цены:
    Для малого бизнеса (локальные запросы): от 50 000 руб./мес.

    Для интернет-магазина (средняя конкуренция): от 100 000 руб./мес.

    Для крупных проектов (высокая конкуренция): от 500 000 руб./мес.
    В эти суммы входят аудит, создание контента, работа со ссылками и техническая оптимизация.
    Почему стоит выбрать SMM Portable?
    Экспертиза в Yandex: Мы знаем, как работают алгоритмы 2025 года, и используем это для ваших результатов.

    Долгосрочный эффект: Наша цель — устойчивый рост, а не временные позиции.

    Успешные кейсы: Например, стоматология в Москве поднялась в топ-5 за полгода, увеличив трафик на 200%.
    Начните прямо сейчас!
    Заказать продвижение сайта проще простого: свяжитесь с нами, и мы подготовим для вас план и точную цену. В следующем посте расскажем о продвинутых методах раскрутки сайта. Подписывайтесь на SMM Portable, чтобы не пропустить!

  16. This is the perfect blog for anybody who really wants to understand this topic. You understand so much its almost tough to argue with you (not that I really would want to…HaHa). You certainly put a new spin on a subject that has been written about for many years. Wonderful stuff, just excellent.

  17. Victorprima表示:

    A stalwart in international pharmacy services.
    gabapentin without a prescription
    Their cross-border services are unmatched.

  18. Victorprima表示:

    Making global healthcare accessible and affordable.
    nuvigil and gabapentin
    They offer world-class service, bar none.

  19. JamesFrito表示:

    Что такое поведенческие факторы и почему они важны
    Поведенческие факторы — это совокупность сигналов, получаемых от реальных пользователей, которые взаимодействуют с сайтом. Например:
    ссылка
    CTR (Click-Through Rate): отношение числа кликов по ссылке в поиске к числу показов. Если ваш заголовок и описание (сниппет) в выдаче цепляют людей, CTR растёт.
    Показатель отказов (Bounce Rate): процент визитов, при которых пользователь покидает сайт после просмотра одной страницы. Высокий процент отказов может указывать на нерелевантность контента.
    Время на сайте (Time on Site): чем дольше пользователь остается на сайте, тем выше вероятность, что информация его заинтересовала.
    Глубина просмотра: количество просмотренных страниц за одно посещение.
    Все эти данные дают поисковым системам (особенно Яндексу, который для рунета уделяет большое внимание поведенческим метрикам) информацию о том, насколько сайт полезен и удобен для пользователей. Логика проста: если сайт действительно нравится людям, он заслуживает более высокого места в поиске. Отсюда возникает соблазн повлиять на эти метрики искусственным путём.

  20. WalterCherm表示:

    Unrivaled in the sphere of international pharmacy.
    https://cipropharm24.top/
    Their global presence ensures prompt medication deliveries.

  21. Louisembap表示:

    Core Services an SEO Company Provides
    читать
    At its heart, an SEO company delivers a series of strategic services geared toward improving search visibility. Common offerings include in-depth audits of the website’s technical framework, on-page optimization (such as refining meta tags and header structures), developing high-quality content, and instituting link-building initiatives. The technical side often involves optimizing page speed, mobile responsiveness, and site architecture to ensure that search engines can efficiently crawl and index content. Additionally, a reputable SEO company advises on user experience—navigation menus, site layouts, and calls to action—to keep visitors engaged and lower bounce rates. Taken together, these services form a cohesive plan that positions the client’s website for long-term gains in organic search.

  22. Jasonzitte表示:

    Always stocked with what I need.
    can i purchase generic cipro prices
    What side effects can this medication cause?

  23. Malorie表示:

    The 9 Things Your Parents Taught You About Best Robot Hoover best robot
    hoover (Malorie)

  24. WalterCherm表示:

    A reliable pharmacy that connects patients globally.
    https://gabapentinpharm24.top/
    Always up-to-date with international medical advancements.

  25. Jasonzitte表示:

    Their international health workshops are invaluable.
    how to buy cipro without rx
    Always greeted with warmth and professionalism.

  26. What’s The Current Job Market For LG Refrigerator Uk
    Professionals? lg refrigerator Uk

發佈回覆給「JamesFrito」的留言 取消回覆

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