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>
Shop Online Google Pay Tools To Ease Your Daily Lifethe
One Shop Online Google Pay Trick That Every Person Should Know shop online
google pay; Cecilia,
1) We couldn’t find this job! Incumbent will conduct the majority of work at the Department of Technology, One South Van Ness Avenue, 2nd Floor. However, there may be situations where the incumbent will be required to work at other sites throughout the City of San Francisco as necessary. The department is currently working in a hybrid model; however, telecommuting options are available upon the appointing officer’s approval and at the appointing officer’s discretion. Confidential,July 2009 to January 2011 Desktop Support Specialist (Contractor) On-site in Knoxville, Tennessee, USA Qualifications for a job description may include education, certification, and experience. Information technology (IT) is one of the fastest-growing fields and it’s projected that there will be over 667,600 new jobs in the industry by 2030. As technology continues to advance at a break-neck speed, skilled IT professionals will be in more demand than ever. That means there’s no better time than now to take the first steps toward training for an entry-level IT job. Here are four reasons to become an IT support specialist today.
https://direct-wiki.win/index.php?title=It_project_planning
Hopefully, this article helped! Please let me know which method helped you, or if you have a better idea on how to fix this issue. I would love your thoughts! In these instances, the computer should otherwise appear to run well. Diagnosis should be easy to reproduce. Simply launch the program for a game or media player, and view in full screen mode. RizTech is proud to offer you superior customer service, the most recommended repair service in NE Ohio with FREE diagnostics and friendly attention to detail all backed with a warranty, savings as EVERYTHING at RizTech is priced below MSRP and we feature NE Ohio’s largest selection of new and refurbished computers to fit any need and every budget. Need a laptop screen repair or laptop screen replacement? Signs you may need a replacement screen for laptop include:
п»їbest mexican online pharmacies: mexican border pharmacies shipping to usa – medication from mexico pharmacy
Добрый день!
Мы предлагаем дипломы любой профессии.
datasheetclub.com/read-blog/85_nadezhnyj-i-proverennyj-onlajn-magazin-s-ogromnym-vyborom-dokumentov
Всегда вам поможем!.
Hey, – Gulvafslibning | Kurt Gulvmand is a tremendously helpful post! Funny, I came over just to make sure I hadn’t missed anything and I come across a really worthwhile post
pharmacies in mexico that ship to usa mexican rx online purple pharmacy mexico price list
could allow go of somebody I cherished, to take on wild adventures I’d certainly not get to get in serious lifetime, to get nightly vacations in the course
Good post. I learn something totally new and challenging on websites I stumbleupon every day. It will always be helpful to read content from other authors and practice a little something from their web sites.
Some genuinely great blog posts on this internet site , regards for contribution.
Здравствуйте!
Полезные советы по покупке диплома о высшем образовании без риска
mandiplomik.ru
pharmacies in mexico that ship to usa: purple pharmacy mexico price list – medicine in mexico pharmacies
medicine in mexico pharmacies: mexico drug stores pharmacies – mexican border pharmacies shipping to usa
Здравствуйте!
Приобрести документ о получении высшего образования вы имеете возможность в нашей компании в Москве.
ast-diplom.com/kupit-diplom-nizhnij-novgorod
Успешной учебы!
Здравствуйте!
Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
newsato.ru/kupit-diplom-garantiya-kachestva-i-bezopasnosti
purple pharmacy mexico price list: medicine in mexico pharmacies – mexico drug stores pharmacies
Здравствуйте!
Купить документ о получении высшего образования вы можете у нас.
ast-diploms.com/kupit-diplom-perm
mexican mail order pharmacies buying from online mexican pharmacy buying prescription drugs in mexico
https://mexicandeliverypharma.com/# buying prescription drugs in mexico online
п»їbest mexican online pharmacies: medicine in mexico pharmacies – mexican pharmaceuticals online
mexican pharmaceuticals online: best online pharmacies in mexico – purple pharmacy mexico price list
Hello there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
Texas Holdem Poker: Essentials 에볼루션 카지노 딜러
Recently, I didnt give lots of thought to leaving comments on site page articles and have placed comments even much less. Reading by means of your nice article, will help me to do so sometimes.
Pretty! This has been a really wonderful article. Thank you for providing these details.
Cool blog. Maybe i can help you in writing fresh content, are you interested ?
buying prescription drugs in mexico mexican mail order pharmacies mexican pharmacy
Здравствуйте!
Приобрести диплом о высшем образовании.
musicianforums.net/index.php?/gallery/image/142-4-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%BD%D1%8B%D1%85-%D0%B3%D1%80%D1%83%D0%BF%D0%BF%D1%8B-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D0%BD%D0%B5%D1%82-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%BE%D0%B2-%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D1%83%D1%8E%D1%89%D0%B8%D1%85-%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B/
Your website does not show up correctly on my apple iphone – you might want to try and fix that
Reese Witherspoon have the most beautiful eyes among american actresses, i just can’t get enough of her beautiful eyes`
http://mexicandeliverypharma.com/# purple pharmacy mexico price list