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>
Spot on with this write-up, I really believe this amazing site requirements far more consideration. I’ll more likely once again you just read a great deal more, many thanks that info.
You got a very excellent website, Gladiolus I observed it through yahoo.
The Reasons To Work With This Does Amazon Ship To Uk Moog 515036 Hub Features
Good work done by the blogger, Keep up the work going………….
You’re making a lot of great points during this blog post however it is very hard in my opinion to concentrate on this article on the complicated page design.
Aw, this was a very nice post. In thought I want to put in writing like this moreover – taking time and precise effort to make an excellent article… but what can I say… I procrastinate alot and under no circumstances appear to get something done.
Excellent points?I would notice that as someone who in reality doesn’t write on blogs a lot (actually, this can be my first publish), I don’t assume the
always choose your travel agency very well, you would not really want to deal with those rip-off travel agents::
Howdy, Might I copy your own picture and implement it on my own blog?
great post, very informative. I’m wondering why the other specialists of this sector do not understand this. You should proceed your writing. I am sure, you’ve a great readers’ base already!
The No. One Question That Everyone Working In Online Shopping Clothes Uk
Cheap Needs To Know How To Answer Vimeo
If you could mail me with a few suggestions on how you made your blog look this excellent, I would be grateful.
What’s up to every body, it’s my first pay a quick visit of this website; this website consists of amazing and truly fine material in favor of visitors.
@@G@@
https://www.bizguru.ru/node/4053
10 Healthy Habits For Where To Buy Electronics Online
Vimeo
What a material of un-ambiguity and preserveness of precious knowledge about unexpected emotions.
@@G@@
https://allaboutourladies.ru/blog/kak-i-zachem-poluchat-virtualnyj-nomer-telefona/
Good ¡V I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Excellent task..
A person necessarily lend a hand to make critically posts I might state. That is the first time I frequented your website page and so far? I amazed with the analysis you made to create this actual put up extraordinary. Great process!
Aw, this became an extremely good post. In notion I must devote writing in this way additionally – spending time and actual effort to make a great article… but exactly what can I say… I procrastinate alot and also by no means often get something carried out.
I just used democratic lunch and we ate barchi sushi. horrible app, but awesome food!|elfreyshira|
rabeprazole 10mg canada – order generic metoclopramide buy domperidone 10mg generic
Hi there! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to resolve this issue. If you have any suggestions, please share. Thanks!
Does Amazon Ship To Uk’s History History Of Does Amazon Ship To Uk Service For 4 Flatware Set
You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!
How To Create Successful Best Online Shopping Sites For Clothes Techniques From
Home air king bfq Series
Is The Craps Field Bet A Sucker Set Your Mind On? 라이브카지노
[53Up.Com]
produce,It happens to be love people raised countless party while in the turntable, the main turntable will not avoid so that the overall victorious one that will not always appreciate what people.
you can say that green health is the best because it is all organic’
В нашем мире, где диплом – это начало удачной карьеры в любом направлении, многие пытаются найти максимально простой путь получения образования. Наличие официального документа сложно переоценить. Ведь диплом открывает двери перед каждым человеком, желающим начать трудовую деятельность или учиться в высшем учебном заведении.
Наша компания предлагает быстро получить этот важный документ. Вы можете заказать диплом, что становится отличным решением для человека, который не смог закончить обучение или потерял документ. Каждый диплом изготавливается аккуратно, с максимальным вниманием к мельчайшим деталям. В результате вы сможете получить полностью оригинальный документ.
Преимущества такого решения заключаются не только в том, что можно максимально быстро получить свой диплом. Процесс организован удобно, с профессиональной поддержкой. От выбора подходящего образца диплома до консультаций по заполнению персональных данных и доставки в любой регион России — все под полным контролем качественных мастеров.
Для всех, кто пытается найти максимально быстрый способ получить требуемый документ, наша услуга предлагает отличное решение. Заказать диплом – это значит избежать долгого процесса обучения и не теряя времени переходить к важным целям: к поступлению в университет или к началу успешной карьеры.
http://diplomsagroups.com/kupit-diplom-vuza/diplom-instituta.html
With the need for men and women these days to remain lovely and youthful always, they have been asked to use the diverse Hgh products in the market right now. Human growth hormone products have been shown to be capable in lessening or avoiding the signs of aging from developing. But with the numerous products sold these days, it’s wise that you study Human growth hormone reviews to assist you determine which best suits your need.
This design is spectacular! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!