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

  1. Richardfek表示:

    вавада казино вавада зеркало вавада зеркало

  2. USATax表示:

    The tension left his shoulders, and a softness returned to his touch after average cost of albuterol inhaler. Say goodbye to doubt and hello to dependable performance.

  3. Dominicerevy表示:

    посмотреть на этом сайте r7 казино игровые автоматы

  4. ZackaryGer表示:

    http://vavadavhod.tech/# вавада зеркало

  5. Dominicerevy表示:

    посмотреть в этом разделе r7 casino демо счет

  6. KennethKex表示:

    пин ап зеркало: пин ап казино – pin up вход

  7. Elmerbuils表示:

    pinup az: pinup az – pin up az

  8. KennethKex表示:

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

  9. Richardfek表示:

    pin up вход пин ап вход пин ап вход

  10. KevinInalm表示:

    Why there’s a huge collection of vintage cars stored in the middle of the desert
    base bridge
    Back at the turn of the 21st century, Qatar was a country with few cultural attractions to keep visitors and residents entertained. Yet the Sheikh Faisal Bin Qassim Al Thani Museum — known as the FBQ Museum — was a place that most people visited as an alternative to the then-still rather ramshackle National Museum of Qatar.

    You had to make an appointment, and drive out into the desert, getting lost a few times along the way, but then you were welcomed to the lush Al Samriya Farm with a cup of tea and some cake. The highlight was being allowed into a space crammed full with shelves and vitrines holding all sorts of eclectic artifacts from swords to coins — with the odd car and carriage standing in the grounds.

    It wasn’t necessarily the kind of museum you’d find elsewhere in the world, but it was definitely a sight that needed seeing.

    Today, it has grown and now claims to be one of the world’s largest private museums. It holds over 30,000 items, including a fleet of traditional dhow sailboats, and countless carpets. There’s also an entire house that once stood in Damascus, Syria.

    There are archaeological finds dating to the Jurassic age, ancient copies of the Quran, a section that details the importance of pearling within Qatar’s history, and jewelry dating to the 17th century.

    There are also items from 2022’s FIFA World Cup in Qatar including replica trophies, balls used in the games, entry passes, football jerseys and even shelves full of slightly creepy dolls and children’s plush animals.

    Some of the more disturbing exhibits include various items of Third Reich paraphernalia in the wartime room, and, strangely enough, several showcases of birds’ legs with marking rings on them. Basically, whatever you can think of, you have a very good chance of finding it here.

    Rumor even has it that behind a locked door is a room filled with the late Princess Diana’s dresses and other memorabilia, accessible only to a select few visitors. Another door hides a room, no longer open to the public, filled with collectibles of the late Saddam Hussein.

  11. FreddieGoatt表示:

    Some scientists believe that fatty acids such as decanoic acid and dodecanoic acid formed the membranes of the first simple cell-like structures on Earth, Pearce said.
    connext network
    “(This is) the closest we’ve come to detecting a major biomolecule-related signal — something potentially tied to membrane structure, which is a key feature of life,” Pearce said via email. “Organics on their own are intriguing, but not evidence of life. In contrast, biomolecules like membranes, amino acids, nucleotides, and sugars are central components of biology as we know it, and finding any of them would be groundbreaking (we haven’t yet).”
    Returning samples from Mars
    The European Space Agency plans to launch its ExoMars Rosalind Franklin rover to the red planet in 2028, and the robotic explorer will carry a complementary instrument to SAM. The rover LS6 will have the capability to drill up to 6.5 feet (2 meters) beneath the Martian surface — and perhaps find larger and better-preserved organic molecules.

    While Curiosity’s samples can’t be studied on Earth, the Perseverance rover has actively been collecting samples from Jezero Crater, the site of an ancient lake and river delta, all with the intention of returning them to Earth in the 2030s via a complicated symphony of missions called Mars Sample Return.
    Both rovers have detected a variety of organic carbon molecules in different regions on Mars, suggesting that organic carbon is common on the red planet, Williams said.

    While Curiosity and Perseverance have proven they can detect organic matter, their instruments can’t definitively determine all the answers about their origins, said Dr. Ashley Murphy, postdoctoral research scientist at the Planetary Science Institute. Murphy, who along with Williams previously studied organics identified by Perseverance, was not involved in the new research.

    “To appropriately probe the biosignature question, these samples require high-resolution and high-sensitivity analyses in terrestrial labs, which can be facilitated by the return of these samples to Earth,” Murphy said.

  12. Dominicerevy表示:

    перейдите на этот сайт r7 casino демо счет

  13. EdwardGraby表示:

    New design revealed for Airbus hydrogen plane
    beefy fi
    In travel news this week: Bhutan’s spectacular new airport, the world’s first 3D-printed train station has been built in Japan, plus new designs for Airbus’ zero-emission aircraft and France’s next-generation high-speed trains.

    Grand designs
    European aerospace giant Airbus has revealed a new design for its upcoming fully electric, hydrogen-powered ZEROe aircraft. powered by hydrogen fuel cells.

    The single-aisle plane now has four engines, rather than six, each powered by their own fuel cell stack.

    The reworked design comes after the news that the ZEROe will be in our skies later than Airbus hoped.

    The plan was to launch a zero-emission aircraft by 2035, but now the next-generation single-aisle aircraft is slated to enter service in the second half of the 2030s.

    Over in Asia, the Himalayan country of Bhutan is building a gloriously Zen-like new airport befitting a nation with its very own happiness index.

    Gelephu International is designed to serve a brand new “mindfulness city,” planned for southern Bhutan, near its border with India.

    In rail travel, Japan has just built the world’s first 3D-printed train station, which took just two and a half hours to construct, according to The Japan Times. That’s even shorter than the whizzy six hours it was projected to take.

    France’s high-speed TGV rail service has revealed its next generation of trains, which will be capable of reaching speeds of up to 320 kilometers an hour (nearly 200 mph).

    The stylish interiors have been causing a stir online, as has the double-decker dining car.

    Finally, work is underway in London on turning a mile-long series of secret World War II tunnels under a tube station into a major new tourist attraction. CNN took a look inside.

  14. Dominicerevy表示:

    перейдите на этот сайт casino r7 игровые автоматы

  15. USATax表示:

    Erectile dysfunction is not failure-it’s a manageable condition improved by ventolin inhaler 200. Real care that fits both your needs and your budget.

  16. ZackaryGer表示:

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

  17. KennethKex表示:

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

  18. Elmerbuils表示:

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

  19. Лучшие проститутки в Сочи, подробнее здесь проститутки сочи

  20. KennethKex表示:

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

  21. Richardfek表示:

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

  22. StevenDuase表示:

    mexican online pharmacy: mexico pharmacies prescription drugs – mexico pharmacies prescription drugs

  23. StevenDuase表示:

    Medicine From India: Medicine From India – indian pharmacy

  24. Премиальные шторы на заказ для вашего интерьера, для вашего дома.
    Качественные шторы на заказ, быстро.
    Создание штор мечты, по вашим размерам.
    Эксклюзивные шторы на заказ, по индивидуальному дизайну.
    Идеальные шторы на заказ для гостиной, под ваш вкус.
    Надежное изготовление штор на заказ, быстро и качественно.
    Заказ штор по проекту клиента, по желанию.
    Модные шторы на заказ, по вашему желанию.
    Современные шторы на заказ, по вашему проекту.
    Создание штор для любого типа окна, от ведущих мастеров.
    Изготовление штор на заказ на любой вкус, с гарантией качества.
    Изготовление штор на заказ быстро и недорого, по вашему желанию.
    Стильные шторы по вашему проекту, под любой стиль интерьера.
    Индивидуальный пошив штор на заказ, по вашему проекту.
    Шторы на заказ с доставкой и монтажом, по мере необходимости.
    Пошив штор на заказ с индивидуальным подходом, по желанию клиента.
    сшить шторы на заказ сшить шторы на заказ . Prokarniz

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

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