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

9,176 Responses

  1. Justinlib表示:

    http://casinositeleri2025.pro/# yeni casino siteleri

  2. Josephnor表示:

    пин ап зеркало: пин ап вход – pinup 2025

  3. TravisFlasp表示:

    pinup2025.com: pinup 2025 – pinup 2025

  4. EdwardApest表示:

    https://slottr.top/# slot tr online

  5. RobertPex表示:

    en cok kazand?ran slot oyunlar? en cok kazand?ran slot oyunlar? en cok kazand?ran slot oyunlar?

  6. RobertPex表示:

    bahis siyeleri deneme bonusu veren yeni casino siteleri by casino

  7. Justinlib表示:

    http://slottr.top/# en cok kazand?ran slot oyunlar?

  8. MichaelSaw表示:

    ‘A short and significant relationship’: How a piano in a pickup builds connections
    Metamask

    Dozens of internationally renowned recording artists give concerts in Vegas every year, but the musician who connects best with people might be a local troubadour who improvises on a piano in the back of his pickup.

    The maestro, Danny Kean, calls his setup The Traveling Piano, and he has traversed North America sharing music for nearly 20 years.

    Kean’s home base is Las Vegas now, and every time he plays, he invites passersby to climb aboard the truck and tickle the ivory for themselves. Even if people are shy or say they can’t do it, Kean usually convinces them to give it a try, inspiring total strangers to express themselves through the common language of music.

    He estimates more than 100,000 people have played his piano since 2006.

    For most of these impromptu virtuosos, the experience is cathartic — many of them step down from the truck in tears. For Kean, 69, the encounters nourish his soul.

    “I enjoy sharing my music with others, but I enjoy having others share theirs with me just as much,” he said. “My goal is to connect with others by creating a short and significant relationship. Music is a great facilitator for that in every way and on every level.”

    Kean does not accept fees or tips for these musical awakenings, giving away time and energy for nothing in return. He practices philanthropy in other ways, too, providing food and other necessities for the burgeoning population of unhoused individuals in downtown Las Vegas and around the Las Vegas Valley.

    “I love the idea of strangers becoming less afraid of each other,” he said. “This love for humanity drives me to keep doing good.”

  9. Josephnor表示:

    bahis veren siteler: yeni siteler bahis – yeni deneme bonusu veren siteler 2025

  10. Justinlib表示:

    https://pinup2025.com/# пинап казино

  11. Michaeltorse表示:

    He thought the guy he met on vacation was just a fling. He turned out to be the love of his life
    Pancakeswap
    Guillermo Barrantes relationship with Larry Mock was supposed to begin and end in Palm Springs.

    It was a “casual, brief encounter.” A vacation dalliance that only lasted half a day.

    “It was just so casual, so easily nothing could have happened from it,” Guillermo tells CNN Travel. “We could have walked away and just had our lives separate. But of course that didn’t happen, because it wasn’t meant to be that way. It was meant to be the way that it was. That it is.”

    It all started in summer 2013. Guillermo – then in his early 40s – was on vacation in the California resort city of Palm Springs. He was in a phase of life where, he says, he was prioritizing himself, and wasn’t interested in long term romance.

    “I thrived in being by myself, in traveling by myself, in having dinner by myself – I loved all of that so much,” says Guillermo, who lived in Boston, Massachusetts at the time.

    “I wanted no commitment, I wanted no emotional entanglement of any kind. I wanted to have fun, get to know myself. And it was in that mode that I met Larry, when I wasn’t really looking.”

    During the vacation in Palm Springs, Guillermo was staying at a friend’s apartment, and while the friend worked during the day, Guillermo passed his time at a “run-down, no-frills” resort a couple of blocks away.

    “You could just pay for a day pass, they’d give you a towel, and you could be in the pool and use their bar,” he recalls.

    One day, as he was walking the palm tree-lined streets to the resort, Guillermo swiped right on a guy on a dating app – Larry Mock, mid-40s, friendly smile. The two men exchanged a few messages back and forth. Larry said he was also on vacation in Palm Springs, staying in the resort Guillermo kept frequenting.

    They arranged to meet there for a drink by the pool. Guillermo was looking forward to meeting Larry, expecting “some casual fun.”

    Then, when Guillermo and Larry met, there was “chemistry” right away. Guillermo calls their connection “magnetic.”

    “My impression of Larry: sexy, handsome and warm,” he recalls.

  12. Justinlib表示:

    http://casinositeleri2025.pro/# welches online casino

  13. RobertPex表示:

    sГјpernetin iddaa siteleri lisanslД± bahis sitesi

  14. Justinlib表示:

    https://slottr.top/# slot siteleri

  15. RobertPex表示:

    пин ап казино пинап казино пин ап зеркало

  16. EdwardApest表示:

    http://pinup2025.com/# пин ап казино зеркало

  17. EdwardApest表示:

    http://casinositeleri2025.pro/# 2025 yatД±rД±m ЕџartsД±z deneme bonusu veren siteler

  18. Josephnor表示:

    en kazancl? slot oyunlar?: en cok kazand?ran slot oyunlar? – en cok kazand?ran slot oyunlar?

  19. Robertwaymn表示:

    Bug-bitten oolong? The secret behind Taiwan’s rare honey-flavored tea — and where to enjoy it
    Ethena

    As the leaves rustle atop the hills in Nantou, Taiwan’s largest tea-producing area, the farm suddenly comes alive, millions of tiny green bugs hopping into the air.

    While many farmers might frown at the sight of these pests munching on their crops, Lee Ming-cheng, a third-generation tea farmer and maker, can’t hide the broad smile on his sun-kissed face.

    This “green insect fog,” as locals call it, is a sign they’ll have a good harvest of Gui Fei Oolong (also known as Honey Flavor Dong Ding Oolong or Concubine Oolong), a special tea that’s prized for offering a hint of honey flavor.

    And it’s these endemic insects, called Jacobiasca formosana, or tea jassids, that are to thank for it.

    When the jassids feed, the leaves go into defensive mode and produce a sweetened hormone that tastes and smells like honey, creating one of the world’s most intriguing teas: mixiang cha, or honey-fragrance tea.

    The bug-bitten leaves are oxidized and roasted to create a variety of beverages. There’s mixiang black tea (made with fully oxidized leaves) and oolong teas like Oriental Beauty (partially oxidized and not roasted) and the previously mentioned Concubine Tea (partially oxidized and roasted), to name a few.

    Unlike Taiwan’s ubiquitous bubble tea, mixiang tea is still highly limited and largely off-the-radar. But what was once a hidden gem among serious tea lovers is now starting to gain international attention.

  20. TravisFlasp表示:

    yeni Гјyelik bonusu veren siteler: bonus veren siteler – slot oyunlarД±

  21. EdwardApest表示:

    http://slottr.top/# slot tr online

  22. Josephnor表示:

    slot oyunlar? puf noktalar?: en cok kazand?ran slot oyunlar? – en kazancl? slot oyunlar?

  23. EdwardBef表示:

    The surprising history of the Fair Isle sweater
    Paris escort directory
    Which fashion item is as beloved by members of the royal family as it is by JLo? Or as relevant on the runways of 2024 as in the knitting catalogs of 1960? The answer is surprisingly festive. The Fair Isle knit, a two-stranded knitting tradition originating off the coast of Scotland, has been a wardrobe staple for well over 100 years — keeping everyone from 18th century fisherman to Mick Jagger warm.

    In the last five years, luxury brands Ralph Lauren, Thom Browne, Chanel, Celine, Balenciaga, Raf Simons, Versace and Dries van Noten have all sent their renditions of the heritage knit down the catwalk. London-based designer Molly Goddard has even made the pattern something of an unofficial signature, making sure to pair a structured Fair Isle-style knit with a flouncy, tulle skirt in almost every collection.

    In short, it has become a winter classic that seems perpetually in vogue. Rom-com leading man, Adam Brody, recently wore a red and white version on the cover of Stylist magazine; while Katie Holmes was snapped running errands in an old beige Fair Isle favorite from 2022.
    For those in the northern hemisphere, it’s appropriate to shrug on as soon as the nights draw in right until sweater weather deteriorates. That being said, even in season-less Los Angeles, stars like Hailey Bieber have been seen in the cozy Fair Isle knits grabbing coffees.

    Taking its name from the island of Fair Isle — part of the Shetland archipelago about 100 miles off the northeastern coast of Scotland — the knitting technique first began in fisherman’s hats during the 18th and 19th century (our beloved sweaters came much later). The two strand pattern was not only artistic, but made the tall, conical shaped caps extra warm by doubling the textile mass. They often featured a knitted interior lining, too.

  24. WesleyBeall表示:

    In China, people are hiring ‘climbing buddies’ for big money. The more attractive they are, the higher the price
    Эскорт-услуги в Израиле
    Wendy Chen decided to challenge herself by climbing Mount Tai, a well-known mountain in eastern China.

    But there was one obstacle in her way: she couldn’t find a friend to join her for the five-hour trek.

    Rather than forgo her plans, the 25-year-old hired a “climbing buddy,” a young man with extensive outdoor experience, to accompany and support her to the 5,000-foot peak.

    Known in Chinese as “pei pa” (meaning “accompany to climb”), these are young Chinese men who join strangers on their journeys up popular mountains for a price. The trend has gained momentum this year, as hashtags related to “climbing buddy” have had over 100 million views on Chinese social media.

    Young, athletic individuals, often university students or even military veterans, advertise themselves on social media platforms like Xiaohongshu and Douyin, with profiles featuring their height, fitness level and hiking experience. They usually charge between 200 to 600 yuan ($30 to $85) per trip.

    During the climb, these “buddies” will do anything to distract their clients from feeling exhausted and push them to keep going: from singing, telling jokes, playing music, verbal encouragement, going so far as carrying their bags, holding their hands, and pulling them.
    A day on the mountain
    Chen and her climbing buddy’s adventure began at around 8:00 pm so she could arrive at the peak in time for the famous sunrise. After assessing her fitness level, her climbing buddy planned a moderate route and carried her backpack the whole way.

    When they faced chilling winds at the peak, Chen’s climbing buddy rented a thick coat for her while directing her to a walled shelter.

    At the moment the sun rose, Chen’s climbing buddy was already prepared with a national flag and other props so that she could take a memorable photo. Though she felt his photography skills still had room to improve, she rated her climbing buddy as “satisfactory.” The service cost her 350 yuan ($49).

    Though Chen paid a typical price for a climbing buddy, she acknowledges that more good-looking buddies can command higher rates.

    “Attractiveness is also part of their strength,” she says.

    Climbing buddies’ main customers tend to be single young women, but that’s slowly changing.

    A video of a strong male university student carrying a three-year-old effortlessly up a steep mountain — while the toddler’s mother trailed far behind — went viral this summer.

  25. Josephnor表示:

    slot oyunlar? puf noktalar?: en kazancl? slot oyunlar? – slot siteleri

  26. TravisFlasp表示:

    en cok kazand?ran slot oyunlar?: slot tr online – slot tr online

  27. Justinlib表示:

    http://slottr.top/# slot oyunlar? puf noktalar?

  28. Josephnor表示:

    bahis siteleri isimleri: en Г§ok kazandД±ran site – slot oyunlarД±nda en Г§ok kazandД±ran oyun

  29. TravisFlasp表示:

    slot oyunlar? puf noktalar?: slot tr online – slot oyunlar?

  30. Justinlib表示:

    http://casinositeleri2025.pro/# yatД±rД±m bonusu veren siteler

發佈留言

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