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>
medication from mexico pharmacy mexico drug stores pharmacies pharmacies in mexico that ship to usa
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервис центры бытовой техники барнаул
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
mexican drugstore online purple pharmacy mexico price list best online pharmacies in mexico
http://drugs24.pro/# herbal ed
top online pharmacy india
I blog often and I really thank you for your content. This article has really peaked my interest. I’m going to book mark your blog and keep checking for new information about once a week. I subscribed to your Feed too.
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервисные центры в челябинске
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту сотовых телефонов в Москве.
Мы предлагаем: сервисы по ремонту телефонов
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
You’ve articulated this issue perfectly.오피
7 simple secrets to eating the Mediterranean way
kraken сайт
What if “diet” wasn’t a dirty word?
During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.
“My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”
But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.
“I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.
Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.
buy prescription drugs from india: best online pharmacy india – india pharmacy
100mg viagra without a doctor prescription https://mexicanpharm24.pro/# buying prescription drugs in mexico online
Sea robins are fish with ‘the wings of a bird and multiple legs like a crab’
kra9.cc
Some types of sea robins, a peculiar bottom-dwelling ocean fish, use taste bud-covered legs to sense and dig up prey along the seafloor, according to new research.
Sea robins are so adept at rooting out prey as they walk along the ocean floor on their six leglike appendages that other fish follow them around in the hope of snagging some freshly uncovered prey themselves, said the authors of two new studies published Thursday in the journal Current Biology.
David Kingsley, coauthor of both studies, first came across the fish in the summer of 2016 after giving a seminar at the Marine Biological Laboratory in Woods Hole, Massachusetts. Kingsley is the Rudy J. and Daphne Donohue Munzer Professor in the department of developmental biology at Stanford University’s School of Medicine.
Before leaving to catch a flight, Kingsley stopped at a small public aquarium, where he spied sea robins and their delicate fins, which resemble the feathery wings of a bird, as well as leglike appendages.
“The sea robins on display completely spun my head around because they had the body of a fish, the wings of a bird, and multiple legs like a crab,” Kingsley said in an email.
“I’d never seen a fish that looked like it was made of body parts from many different types of animals.”
Kingsley and his colleagues decided to study sea robins in a lab setting, uncovering a wealth of surprises, including the differences between sea robin species and the genetics responsible for their unusual traits, such as leglike fins that have evolved so that they largely function as sensory organs.
The findings of the study team’s new research show how evolution leads to complex adaptations in specific environments, such as the ability of sea robins to be able to “taste” prey using their quickly scurrying and highly sensitive appendages.
7 simple secrets to eating the Mediterranean way
kraken зайти
What if “diet” wasn’t a dirty word?
During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.
“My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”
But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.
“I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.
Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.
indian pharmacies safe mail order pharmacy india reputable indian online pharmacy
Sea robins are fish with ‘the wings of a bird and multiple legs like a crab’
kra10.cc
Some types of sea robins, a peculiar bottom-dwelling ocean fish, use taste bud-covered legs to sense and dig up prey along the seafloor, according to new research.
Sea robins are so adept at rooting out prey as they walk along the ocean floor on their six leglike appendages that other fish follow them around in the hope of snagging some freshly uncovered prey themselves, said the authors of two new studies published Thursday in the journal Current Biology.
David Kingsley, coauthor of both studies, first came across the fish in the summer of 2016 after giving a seminar at the Marine Biological Laboratory in Woods Hole, Massachusetts. Kingsley is the Rudy J. and Daphne Donohue Munzer Professor in the department of developmental biology at Stanford University’s School of Medicine.
Before leaving to catch a flight, Kingsley stopped at a small public aquarium, where he spied sea robins and their delicate fins, which resemble the feathery wings of a bird, as well as leglike appendages.
“The sea robins on display completely spun my head around because they had the body of a fish, the wings of a bird, and multiple legs like a crab,” Kingsley said in an email.
“I’d never seen a fish that looked like it was made of body parts from many different types of animals.”
Kingsley and his colleagues decided to study sea robins in a lab setting, uncovering a wealth of surprises, including the differences between sea robin species and the genetics responsible for their unusual traits, such as leglike fins that have evolved so that they largely function as sensory organs.
The findings of the study team’s new research show how evolution leads to complex adaptations in specific environments, such as the ability of sea robins to be able to “taste” prey using their quickly scurrying and highly sensitive appendages.
ed devices http://drugs24.pro/# online drugstore
Comet likely last seen when Neanderthals walked Earth could soon dazzle in the night sky
Смартфон OnePlus Nord CE 3 Lite 5G 8GB/128GB графит глобальная версия купить в рассрочку
A recently discovered comet, known as C/2023 A3 Tsuchinshan–ATLAS, will make its closest approach of Earth on Saturday. Sky-gazers won’t want to miss the event since it may be the last time the comet will be seen in the night sky for another 80,000 years.
The comet successfully reached perihelion, its closest point to the sun in its orbital path around the parent star, on September 27, and was visible for those in the Southern Hemisphere in September and early October. Now, the icy body is on its way out of the inner solar system and will be visible to those in the Northern Hemisphere in mid-October through early November, according to NASA.
On Saturday, the comet will come within about 44 million miles (nearly 71 million kilometers) of Earth. The comet is making its first documented flyby of our planet, according to NASA. With its 80,000-year orbit, the celestial body would have been last seen from Earth at the time of the Neanderthals.
Those looking to catch a glimpse of the once-in-a-lifetime event will want to look in the western part of the night sky, shortly after sunset, according to EarthSky.
The comet will look like a bright fireball in the dark sky with a long, extended tail. Bill Cooke, lead of NASA’s Meteoroid Environment Office at the Marshall Space Flight Center in Huntsville, Alabama, recommends a pair of binoculars for enhanced viewing of the comet.
“It’s not going to zing across the sky like a meteor. It will just appear to hang there, and it will slowly change position from night to night,” Cooke said. “If you can see (the comet) with your unaided eye, (using) the binoculars will knock your socks off.”
mexican pharmaceuticals online: medicine in mexico pharmacies – mexican drugstore online
indianpharmacy com indian pharmacies safe indianpharmacy com
https://drugs24.pro/# 100mg viagra without a doctor prescription
buy medicines online in india
indian pharmacy online: best online pharmacy india – top 10 pharmacies in india
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: ремонт крупногабаритной техники в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
7 simple secrets to eating the Mediterranean way
kraken сайт
What if “diet” wasn’t a dirty word?
During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.
“My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”
But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.
“I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.
Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: ремонт крупногабаритной техники в барнауле
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Automatic takeoffs are coming for passenger jets and they’re going to redraw the map of the sky
kra10 cc
In late 1965, at what’s now London Heathrow airport, a commercial flight coming from Paris made history by being the first to land automatically.
The plane – A Trident 1C operated by BEA, which would later become British Airways – was equipped with a newly developed extension of the autopilot (a system to help guide the plane’s path without manual control) known as “autoland.”
Today, automatic landing systems are installed on most commercial aircraft and improve the safety of landings in difficult weather or poor visibility.
Now, nearly 60 years later, the world’s third largest aircraft manufacturer, Brazil’s Embraer, is introducing a similar technology, but for takeoffs.
Called “E2 Enhanced Take Off System,” after the family of aircraft it’s designed for, the technology would not only improve safety by reducing pilot workload, but it would also improve range and takeoff weight, allowing the planes that use it to travel farther, according to Embraer.
“The system is better than the pilots,” says Patrice London, principal performance engineer at Embraer, who has worked on the project for over a decade. ”That’s because it performs in the same way all the time. If you do 1,000 takeoffs, you will get 1,000 of exactly the same takeoff.”
Embraer, London adds, has already started flight testing, with the aim to get it approved by aviation authorities in 2025, before introducing it from select airports.
http://drugs24.pro/# drug store online
india pharmacy
ed pills online pharmacy: ed treatment natural – website
buy medicines online in india: reputable indian pharmacies – cheapest online pharmacy india
An impressive share! I have just forwarded this onto a colleague who was conducting a little research on this. And he in fact bought me dinner because I found it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanks for spending some time to discuss this issue here on your site.
indian pharmacy paypal best online pharmacy india buy prescription drugs from india