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

  1. MichaelJed表示:

    Curious about DeFi? Juice Finance is shaking up the space with its powerful Juice Finance DeFi platform. With smart Juice Finance lending, high Juice Finance APY, and seamless Juice Finance staking, users are maximizing returns with ease. Built for security and performance, the Juice Finance app offers features like Juice Finance cross-margin lending and Juice Finance on Blast L2. Wondering what is Juice Finance? Check the Juice Finance FAQ or read the Juice Finance Blog. Ready to earn more? Juice Finance mobile app is live—get started at https://juice.ac today!

  2. Brianbleft表示:

    Exploring cross-chain swaps? ThorSwap is redefining DeFi with its powerful ThorSwap DEX and seamless ThorSwap Exchange. With ThorSwap Cross-Chain support and the ThorSwap Aggregator, users enjoy top liquidity across multiple networks. Curious about ThorSwap Security or ThorSwap Fees? It’s safe, efficient, and transparent. Want to learn more? ThorSwap Tutorial and ThorSwap Guide make it easy. Ready to trade? ThorSwap App is live—join now at https://thorswap.cc and take full control of your crypto journey!

  3. JamesMaf表示:

    New to DeFi? Instadapp is transforming decentralized finance with its all-in-one platform. From Instadapp Pro to Instadapp Lite, users can manage assets with ease using Instadapp Avocado Wallet and Instadapp Fluid. Packed with powerful tools like Instadapp Flashloan and DeFi Smart Accounts (DSA), it’s the smartest way to move assets. Curious about what is Instadapp? Check the Instadapp overview or dive into the Instadapp App. Want to know how to use Instadapp? It’s easy—get started now at http://instaoapp.com and take full control of your DeFi future today!

  4. Victorsox表示:

    Say hello to Super Sushi Samurai—the ultimate crypto game experience! Earn with Super Sushi Samurai land, explore the Super Sushi Samurai land map, and boost your gameplay using Super Sushi Samurai strategy and Super Sushi Samurai tips. Whether you’re collecting Super Sushi Samurai NFT items or gearing up for the Super Sushi Samurai airdrop, the SSS game delivers nonstop action. Want in? Buy SSS token and join the community on Super Sushi Samurai Telegram. Play now at https://sssgame.ink !

  5. Jamestonse表示:

    RingExchange is here to redefine crypto trading. With deep liquidity from the RingX Aggregator and a smooth Ring Exchange DEX interface, users enjoy top-tier execution across chains. Use the Ring Exchange tutorial to get started, and take full advantage of Ring Exchange crypto tools. From RING crypto to the trusted Ring Exchange BNB Chain support, it’s built to scale. Curious about ProtocolRing? It’s all part of the vision. Visit https://ringexchange.org and explore Ring Exchange DeFi today!

  6. Jamestonse表示:

    Exploring new DeFi tools? Ring Exchange is changing the game with its all-in-one Ring Exchange DEX and RingX Aggregator. From Ring Exchange staking to low Ring Exchange fees, it’s built for serious traders. Powered by Ring Protocol and the RING token, you get efficient swaps across chains like Ring Exchange BNB Chain and Ring Exchange Blast. Curious about Ring Exchange review? Users love the speed, design, and Ring Exchange security. Want to learn more? Check the Ring Exchange tutorial and start now at https://ringexchange.org !

  7. JesseHef表示:

    Josh Giddey hits halfcourt buzzer-beater over LeBron James to cap wild finale as the Bulls stun the Lakers
    quickswap
    Josh Giddey hit a game-winning, halfcourt buzzer-beater over LeBron James as the Chicago Bulls stunned the Los Angeles Lakers in one of the wildest endings to an NBA game you are ever likely to see.

    Trailing 115-110 with 12.6 seconds remaining, Giddey’s inbound pass found Nikola Vucevic, who pushed the ball to a wide-open Patrick Williams for a corner three-pointer.

    James then fluffed the Lakers inbound pass from the baseline, allowing Giddey to steal the ball and find Coby White for a second Bulls triple in quick succession to put Chicago up 116-115 with 6.1 seconds remaining.
    Austin Reaves then made a driving layup to put the Lakers ahead 117-116 with 3.3 seconds left, but the game wasn’t done yet.

    With no timeouts remaining, Giddey inbounded the ball to Williams from the baseline, got the pass back, took one dribble and launched a shot from beyond halfcourt.

    Supporters in the stands seemed frozen in anticipation as the ball sailed through the air, and the United Center then erupted as it fell through the net. After the dramatic win, Giddey found himself being swarmed by his teammates.

    “Special moment to do it with these guys, this team,” Giddey said, per ESPN. “We’ve shown over the last month to six weeks that we can beat anybody. The way we play the game, I think it wears people down.

    “We get up and down. We run. We put heat on them to get back. A lot of veteran teams don’t particularly want to get back and play in transition.”

    Giddey later told the Bulls broadcast that he’d “never made a game-winner before.”

    The ending capped an incredible couple of games for the Lakers, who had themselves won their last game against the Indiana Pacers on Wednesday with a buzzer-beating tip-in from James.

  8. Billynot表示:

    Mist and microlightning
    solflare
    To recreate a scenario that may have produced Earth’s first organic molecules, researchers built upon experiments from 1953 when American chemists Stanley Miller and Harold Urey concocted a gas mixture mimicking the atmosphere of ancient Earth. Miller and Urey combined ammonia (NH3), methane (CH4), hydrogen (H2) and water, enclosed their “atmosphere” inside a glass sphere and jolted it with electricity, producing simple amino acids containing carbon and nitrogen. The Miller-Urey experiment, as it is now known, supported the scientific theory of abiogenesis: that life could emerge from nonliving molecules.
    For the new study, scientists revisited the 1953 experiments but directed their attention toward electrical activity on a smaller scale, said senior study author Dr. Richard Zare, the Marguerite Blake Wilbur Professor of Natural Science and professor of chemistry at Stanford University in California. Zare and his colleagues looked at electricity exchange between charged water droplets measuring between 1 micron and 20 microns in diameter. (The width of a human hair is 100 microns.)

    “The big droplets are positively charged. The little droplets are negatively charged,” Zare told CNN. “When droplets that have opposite charges are close together, electrons can jump from the negatively charged droplet to the positively charged droplet.”
    The researchers mixed ammonia, carbon dioxide, methane and nitrogen in a glass bulb, then sprayed the gases with water mist, using a high-speed camera to capture faint flashes of microlightning in the vapor. When they examined the bulb’s contents, they found organic molecules with carbon-nitrogen bonds. These included the amino acid glycine and uracil, a nucleotide base in RNA.

    “We discovered no new chemistry; we have actually reproduced all the chemistry that Miller and Urey did in 1953,” Zare said. Nor did the team discover new physics, he added — the experiments were based on known principles of electrostatics.

    “What we have done, for the first time, is we have seen that little droplets, when they’re formed from water, actually emit light and get this spark,” Zare said. “That’s new. And that spark causes all types of chemical transformations.”

  9. ZackaryGer表示:

    http://pinuprus.pro/# пин ап зеркало

  10. HerbertDrilk表示:

    A tiny rainforest country is growing into a petrostate. A US oil company could reap the biggest rewards
    swell network
    Guyana’s destiny changed in 2015. US fossil fuel giant Exxon discovered nearly 11 billion barrels of oil in the deep water off the coast of this tiny, rainforested country.

    It was one of the most spectacular oil discoveries of recent decades. By 2019, Exxon and its partners, US oil company Hess and China-headquartered CNOOC, had started producing the fossil fuel.? They now pump around 650,000 barrels of oil a day, with plans to more than double this to 1.3 million by 2027.

    Guyana now has the world’s highest expected oil production growth through 2035.

    This country — sandwiched between Brazil, Venezuela and Suriname — has been hailed as a climate champion for the lush, well-preserved forests that carpet nearly 90% of its land. It is on the path to becoming a petrostate at the same time as the impacts of the fossil fuel-driven climate crisis escalate.

    While the government says environmental protection and an oil industry can go hand-in-hand, and low-income countries must be allowed to exploit their own resources, critics say it’s a dangerous path in a warming world, and the benefits may ultimately skew toward Exxon — not Guyana.

  11. VernonPap表示:

    Marinade Finance is here to transform Solana staking! With high Marinade Finance APY, secure Marinade Audits, and community-backed Marinade DAO, it’s trusted by thousands. Whether you’re using the Marinade app, holding Marinade Finance token, or exploring Marinade liquid staking, it’s all designed for your growth. Marinade Finance safe? Absolutely. Ready to start? Visit https://marinade.ink and stake your Marinade SOL smarter today!

  12. Richardfek表示:

    вавада казино вавада зеркало вавада официальный сайт

  13. KennethKex表示:

    pin-up casino giris: pin up casino – pin up

  14. Robertdom表示:

    Looking to maximize your DeFi game? Explore Balancer, the ultimate platform for smart liquidity and optimized portfolios. With advanced Balancer features like Balancer Swap, Balancer stable pools, and Balancer Boost, it’s built for efficiency and control. Curious about Balancer token vesting or Balancer DAO vesting? The Balancer guide has it all. Plus, with Balancer security and top-notch Balancer governance, your assets are in good hands. Visit https://balancer.ac and experience the future of DeFi today!

  15. AnthonyFat表示:

    Scientists redid an experiment that showed how life on Earth could have started. They found a new possibility
    safepal wallet
    In the 1931 movie “Frankenstein,” Dr. Henry Frankenstein howling his triumph was an electrifying moment in more ways than one. As massive bolts of lightning and energy crackled, Frankenstein’s monster stirred on a laboratory table, its corpse brought to life by the power of electricity.

    Electrical energy may also have sparked the beginnings of life on Earth billions of years ago, though with a bit less scenery-chewing than that classic film scene.

    Earth is around 4.5 billion years old, and the oldest direct fossil evidence of ancient life — stromatolites, or microscopic organisms preserved in layers known as microbial mats — is about 3.5 billion years old. However, some scientists suspect life originated even earlier, emerging from accumulated organic molecules in primitive bodies of water, a mixture sometimes referred to as primordial soup.

    But where did that organic material come from in the first place? Researchers decades ago proposed that lightning caused chemical reactions in ancient Earth’s oceans and spontaneously produced the organic molecules.

    Now, new research published March 14 in the journal Science Advances suggests that fizzes of barely visible “microlightning,” generated between charged droplets of water mist, could have been potent enough to cook up amino acids from inorganic material. Amino acids — organic molecules that combine to form proteins — are life’s most basic building blocks and would have been the first step toward the evolution of life.

  16. Rikvip表示:

    rikvipb.com bảo mật giao dịch đạt chuẩn quốc tế

  17. KennethKex表示:

    вавада казино: вавада официальный сайт – vavada вход

  18. BrianStani表示:

    вавада: вавада казино – вавада

  19. Elmerbuils表示:

    пин ап казино: пин ап казино – пин ап казино официальный сайт

  20. ZackaryGer表示:

    http://pinupaz.top/# pinup az

  21. Elmerbuils表示:

    пин ап вход: пинап казино – пинап казино

  22. JoshuaTic表示:

    Exploring DeFi? Compound is changing the game with powerful Compound Finance tools designed for real results. Through the Compound app, users enjoy smart Compound lending, easy Compound borrowing, and competitive Compound interest rates. The Compound protocol is built on transparency, using Compound cTokens and driven by Compound governance. Want to grow your earnings? With high Compound APY and support for Compound Finance staking, you’re in control. Curious about Compound Finance review? Users love the security and reliability. Try it now—Compound Finance login at http://compound.ad and take charge of your Compound crypto journey today!

  23. JosephSward表示:

    Power up your crypto strategy with Balancer—where flexibility meets innovation. Use Balancer Swap to trade smarter, explore Balancer vesting options, and stay on top of the game with Balancer Change updates. With features like Balancer governance, Balancer token vesting, and detailed Balancer guide content, it’s built for both beginners and pros. Love transparency? So do we. That’s why Balancer reviews speak for themselves. Start now at https://bccgame.org and take control of your crypto future.

  24. Prokarniz表示:

    Автоматизация дома — просто с Somfy
    Автоматика Somfy Автоматика Somfy . +7 (499) 638-25-37

  25. VernonPap表示:

    Looking to stake on Solana? Marinade Finance is leading the charge with trusted, non-custodial Marinade liquid staking. Stake with ease using the Marinade app and earn yield through Marinade mSOL—all while keeping control of your assets. Curious about Marinade Finance review? Users love the performance, transparency, and safety. Want to know how to Marinade Stake SOL? It’s simple—connect your wallet and start staking. Ready to earn? Visit https://marinade.ink and boost your Marinade Yield today!

  26. Jamestonse表示:

    Say hello to Ring Exchange—the DeFi platform made for next-gen crypto users. Whether you’re trading on the Ring Exchange aggregator, exploring Ring Protocol crypto, or earning with Ring Exchange staking, the experience is seamless. Ring Exchange launchpad opens new project access, while the RING token powers the ecosystem. Wondering how it compares? See why traders are switching in every Ring Exchange review. Start your journey now at https://ringexchange.org !

  27. JoshuaTic表示:

    Compound Finance is redefining decentralized finance! With powerful Compound DeFi tools, competitive Compound interest rates, and reliable Compound APY, it’s a go-to for crypto users everywhere. Whether you’re staking COMP token, using Compound Finance wallet, or exploring Compound alternatives, this platform has it all. Need guidance? The Compound Finance tutorial makes it easy, and every Compound Finance review proves its value. From Compound lending to Compound borrowing, it’s built on the trusted Compound protocol. Compound where to start? Visit http://compound.ad and join the Compound crypto revolution today!

  28. Vernonneato表示:

    New to trading on Solana? Phoenix Trade is leading the way with a high-speed, zero-order book Solana DEX experience. Built for power users, Phoenix Trade offers deep liquidity, lightning-fast execution, and secure Phoenix Trade Wallet integration. Curious about Phoenix Trade Review? Traders love the platformтАЩs low Phoenix Trade Fees and solid Phoenix Trade Security. Want to know Phoenix Trade Tutorial? ItтАЩs simpleтАФjust Phoenix Trade Login and explore the features. Ready to start? Visit https://phoenixtrade.me and experience the future of decentralized trading today!

  29. WilliamWhesy表示:

    “You have a government that is reckless about what is going to happen to Guyana,” said Melinda Janki, an international lawyer in Guyana who is handling several lawsuits against Exxon. It’s pursuing “a supposed course of development that is actually backward and destructive,” she told CNN.
    kelp dao
    And while plenty of Guyanese people welcome the new oil industry, some say Guyana’s startling economic statistics do not reflect a real-world prosperity for ordinary people, many of whom are struggling with the higher prices accompanying the oil boom. Inflation rose 6.6% in 2023, with prices of some foods shooting up much more rapidly.

    “Since the oil extraction began in Guyana, we have noticed that our cost of living has gone sky high,” said Wintress White, of Red Thread, a non-profit that focuses on improving living conditions for Guyanese women. “The money is not trickling down to the masses,” she told CNN.

    CNN contacted President Ali, the Ministry of Natural Resources and the Ministry of Finance for comment but received no response.
    Guyana, a former Dutch then British colony which gained independence in 1966, is one of only a handful of countries that is a “carbon sink,” meaning it stores more planet-heating pollution than it produces. This is due to its vast rainforest; trees remove carbon dioxide from the atmosphere as they grow.

    The country has protected its biodiversity where others have destroyed theirs, President Ali said in a BBC interview last year. In 2009, the country signed an agreement with Norway, which promised Guyana more than $250 million to preserve its 18.5 million hectares, or nearly 46 million acres, of forests.

    Ali insists the country can balance climate leadership and fossil fuel exploitation. The new oil wealth will allow Guayana to develop, including building climate adaptations such as sea walls, he has said. He has also pointed to the continued failures of wealthy countries, already grown rich on their own fossil fuels, to help poorer countries with climate finance.

    But there are concerns Guyana could fall victim to the “resource curse,” in which vast, new wealth ?can actually make life worse for those who live there.

  30. ZackaryGer表示:

    http://pinuprus.pro/# пин ап казино

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

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