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

  1. Josephnor表示:

    en cok kazand?ran slot oyunlar?: az parayla cok kazandiran slot oyunlar? – slot siteleri

  2. EdwardApest表示:

    http://casinositeleri2025.pro/# 2025 bahis siteleri deneme bonusu

  3. EdwardApest表示:

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

  4. Josephnor表示:

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

  5. Justinlib表示:

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

  6. TravisFlasp表示:

    pinup2025.com: pinup 2025 – pinup 2025

  7. EdwardApest表示:

    https://slottr.top/# slot oyunlar?

  8. Zydddi表示:

    order provigil generic – epivir price epivir where to buy

  9. Justinlib表示:

    http://casinositeleri2025.pro/# casino en iyi siteler

  10. RobertPex表示:

    en yeni deneme bonusu veren siteler 2025 en kaliteli bahis siteleri yasal casino siteleri

  11. Justinlib表示:

    https://casinositeleri2025.pro/# oyun inceleme siteleri

  12. Josephnor表示:

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

  13. JamesAreft表示:

    They fell in love three decades ago. Now they pilot planes together
    Aave

    On their first flight together, Joel Atkinson and Shelley Atkinson couldn’t contain their excitement. They enthused to the flight attendants. They posed for photos. They told passengers via a pre-flight announcement.

    “We made a big deal about it,” Joel tells CNN Travel.

    Then, right before take off, Joel and Shelley sat side by side in the flight deck, just the two of them. They’d come full circle, and were about to embark on an exciting new chapter.

    “It felt amazing,” Shelley tells CNN Travel.

    “As we prepared to take off, I was giddy, euphoric,” says Joel.

    Joel and Shelley met as twentysomethings flying jets in the US Air Force. They became fast friends, then, over time, fell in love.

    Today, they’ve been married for 27 years and counting. They’ve brought up two kids together. And now they’re both pilots for Southwest Airlines. They regularly fly together, with Joel as captain and Shelley as first officer.

    The couple say working together is “amazing.” They treat layovers as “date nights.” They learn from one another’s respective “wisdom and judgment.”

    And no, they don’t argue mid-flight.

    “People ask us, how does it work, flying together?” says Joel. “We know a few pilot couples and some of them fly together, some of them don’t. I’ve heard people say, ‘Oh I could never fly with my wife or my husband.’”

    For Joel and Shelley, working together is seamless – a joy that comes easily to them both.

    “We’re best friends,” says Shelley.

    “There’s just that unspoken bond,” says Joel.

  14. TravisFlasp表示:

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

  15. Josephnor表示:

    пин ап казино: пинап казино – pinup 2025

  16. Justinlib表示:

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

  17. RobertPex表示:

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

  18. Josephnor表示:

    en cok kazand?ran slot oyunlar?: slot oyunlar? – az parayla cok kazandiran slot oyunlar?

  19. Justinlib表示:

    http://casinositeleri2025.pro/# bonus veren bahis siteleri yasal

  20. TravisFlasp表示:

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

  21. Chesterfeank表示:

    You’ve come across a bison in the wild. It’s looking at you. Do you know what to do next?
    Pendle

    A dangerous encounter with a territorial bison and the subsequent viral video were not what Rebecca Clark had in mind when she set out for Caprock Canyons State Park in early October 2022.

    She had been so enamored with Texas’ third-largest state park on her first solo hiking and camping trip there a year earlier that she decided to go back for more. Roughly two hours by car from either Lubbock or the Panhandle city of Amarillo, Caprock attracts visitors with big blue skies, brown and green prairielands and rugged red-rock formations.

    Caprock has another draw – its wild bison herd, about 350 strong in late 2022. But bison, the great symbolic animal of the Great Plains, weren’t on her radar. Until suddenly, they were.

    The Texas resident recounted her experience with CNN’s Ed Lavandera, telling him that she came upon a herd while she was walking a trail back from Lake Theo.

    “I decided to just kind of wait for them to … get across the trail, and then I would pass them.” But they weren’t moving away fast enough for Clark. She said she decided to just walk by them – closer than the recommended safety distance. She was recording the moment on her smartphone.

    In her video, Clark can be heard saying, “Thank you, I appreciate it” as she passes the animals.

    Things got dangerous very quickly when one of the agitated bison took notice. “When I saw him turn, it’s like instantly I knew he was gonna come after me.”

    And that’s exactly what the bison did. Once it charged, the large mammal was upon Clark within two seconds despite her frantic attempt to flee.

    “It was so fast. He hit me in the back, rammed me, hooked me, then flipped me up and face forward into the mesquite bush.”

    And there was Clark. Gored, bleeding and alone. How would she survive?

  22. RobertPex表示:

    пин ап казино пин ап казино pinup 2025

  23. Anthonyacawl表示:

    How to survive a bear attack – or better yet, avoid one altogether
    Uniswap

    You’re out for a hike, reveling in glorious nature. Suddenly, you spot a bear. And the bear has spotted you, too. Would you know what to do next?

    Beth Pratt sure would.

    She was once on the Old Gardiner Road Trail in Yellowstone National Park, enjoying her run in wild nature. Her reverie came to an end when she came upon a grizzly bear eating flowers.

    “I stopped. It stood on its hind legs and looked at me. I knew that wasn’t a threatening gesture,” she told CNN Travel. “I’m not kidding, it waved its paw at me as if to say, ‘just go on your way,’ and went back to eating.”

    “And I walked slowly away and put some distance between us, and the encounter ended fine.”

    When it comes to dealing with bears, Pratt does have a thing or two on almost all the rest of us, though.

    She is the California regional executive director for the National Wildlife Federation, a job she’s had for more than 10 years. She worked in Yellowstone for several years – and once saw nine grizzlies in one day there.
    Finally, she lives on the border of Yosemite National Park, and bears will pass through her yard, including this one seen in the footage above in late September 2021.

    You can hear the enthusiasm in Pratt’s voice as she shares her bear bona fides and advice to make sure bear/human encounters are delightful, not dangerous.

    “A wild bear is a beautiful sight to see. It’s incredible to see them in the wild. I never had a bad experience with bears. What I try to get people to feel is respect, not fear, for bears. The animal usually wants to avoid the encounters.”

  24. Justinlib表示:

    https://slottr.top/# slot siteleri

  25. Josephnor表示:

    en kazancl? slot oyunlar?: slot tr online – slot tr online

  26. RobertPex表示:

    bonus veren siteler yeni tГјm casino siteleri deneme bonusu bahis siteleri

  27. TravisFlasp表示:

    пинап казино: пинап казино – pinup 2025

  28. Justinlib表示:

    http://casinositeleri2025.pro/# casino giriЕџ

  29. Josephnor表示:

    slot tr online: slot tr online – az parayla cok kazandiran slot oyunlar?

  30. TravisFlasp表示:

    yeni siteler: gГјvenilir siteler – 100 tl bonus veren bahis siteleri

發佈留言

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