Java uses DOM to add, delete, modify, and query the XML document. domxml

Source: Internet
Author: User

Java uses DOM to add, delete, modify, and query the XML document. domxml

This article focuses on the code for adding, deleting, modifying, and querying XML documents using DOM in java. The specific example is as follows.

Source code:

Package com. zc. homeWork18; import java. io. file; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import javax. xml. transform. transformer; import javax. xml. transform. transformerFactory; import javax. xml. transform. dom. DOMSource; import javax. xml. transform. stream. streamResult; import javax. xml. xpath. XPath; import javax. xml. xpath. XPathConstants; import javax. xml. xpath. XPa ThExpressionException; import javax. xml. xpath. XPathFactory; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList; public class XMLWriter {private static String xmlPath = "src \ com \ zc \ homeWork18 \ MyXml. xml "; public static void getFamilyMemebers () {/** create a file factory instance */DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); // If the created parser is in In XML documents, spaces in the element content must be deleted. The value is true. Otherwise, the value is false dbf. setIgnoringElementContentWhitespace (true); try {/** Create File object */DocumentBuilder db = dbf. newDocumentBuilder (); // create a parser to parse the XML Document doc = db. parse (xmlPath); // use dom to parse xml files/** calendar list, extract data from the XML file * // obtain all related nodes according to the node name NodeList sonlist = doc. getElementsByTagName ("son"); for (int I = 0; I <sonlist. getLength (); I ++) // cyclically processed object {// processing Element son = (El Ement) sonlist. item (I); // All subnodes IN THE son Node of the cyclic node for (node Node = son. getFirstChild (); node! = Null; node = node. getNextSibling () {// determine whether it is an element node if (node. getNodeType () = Node. ELEMENT_NODE) {String name = node. getNodeName (); String value = node. getFirstChild (). getNodeValue (); System. out. println (name + ":" + value) ;}}} catch (Exception e) {System. out. println (e. getMessage () ;}}// modify public static void modifySon () {// create a file factory instance DocumentBuilderFactory dbf = DocumentBuilderFactory. NewInstance (); dbf. setIgnoringElementContentWhitespace (true); try {// obtain the DOM document instance DocumentBuilder db = dbf from the XML document. newDocumentBuilder (); // obtain the Document Object Document xmldoc = db. parse (xmlPath); // get the root node Element root = xmldoc. getDocumentElement (); // locate the node Element with id 001 per = (Element) selectSingleNode ("/father/son [@ id = '001']", root ); // change the content of the age node to 28 per. getElementsByTagName ("age "). item (0 ). setTextCont Ent ("28"); // save TransformerFactory factory = TransformerFactory. newInstance (); Transformer former = factory. newTransformer (); former. transform (new DOMSource (xmldoc), new StreamResult (new File (xmlPath);} catch (Exception e) {System. out. println (e. getMessage () ;}// get the target node, delete it, and save the public static void discardSon () {DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); dbf. setIg NoringElementContentWhitespace (true); try {DocumentBuilder db = dbf. newDocumentBuilder (); Document xmldoc = db. parse (xmlPath); // get the root node Element root = xmldoc. getDocumentElement (); // locate the node Element son = (Element) selectSingleNode ("/father/son [@ id = '002']", root); // Delete the node root. removeChild (son); // save TransformerFactory factory = TransformerFactory. newInstance (); Transformer former = fac Invalid. newTransformer (); former. transform (new DOMSource (xmldoc), new StreamResult (new File (xmlPath);} catch (Exception e) {System. out. println (e. getMessage () ;}}// add public static void createSon () {// create a file factory instance DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); dbf. setIgnoringElementContentWhitespace (false); try {DocumentBuilder db = dbf. newDocumentBuilder (); // create a Document Object Document xmldoc = db. parse (xmlPath); // get the root node Element root = xmldoc. getDocumentElement (); // create a node son and set the corresponding id to 004 Element son = xmldoc. createElement ("son"); son. setAttribute ("id", "004"); // create a node name Element name = xmldoc. createElement ("name"); name. setTextContent ("Youngest son"); son. appendChild (name); // create a node age Element age = xmldoc. createElement ("age"); age. setTextContent ("0"); son. appendChild (age );/ /Add son to the root node as root. appendChild (son); // save TransformerFactory factory = TransformerFactory. newInstance (); Transformer former = factory. newTransformer (); former. transform (new DOMSource (xmldoc), new StreamResult (new File (xmlPath);} catch (Exception e) {System. out. println (e. getMessage () ;}}// modify Node information public static Node selectSingleNode (String express, Element source) {Node result = null; // create XPathFactory xpathFactory = XPathFactory. newInstance (); // create the XPath object XPath xpath = xpathFactory. newXPath (); try {result = (Node) xpath. evaluate (express, source, XPathConstants. NODE); System. out. println (result);} catch (XPathExpressionException e) {System. out. println (e. getMessage ();} return result;} // print public static void main (String [] args) {getFamilyMemebers (); System. out. println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~ "); ModifySon (); System. out. println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ "); System. out. println ("modify data"); getFamilyMemebers (); System. out. println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ "); DiscardSon (); System. out. println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ "); System. out. println ("delete data"); getFamilyMemebers (); System. out. println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ "); CreateSon (); System. out. println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ "); System. out. println (" add data "); getFamilyMemebers ();}}

XML file

<? Xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <Father> <son id = "001"> <name> boss </name> <age> 20 </age> </son> <son id = "002"> <name> Second Child </name> <age> 18 </age> </son> <son id = "003"> <name> old three </name> <age> 13 </age> </son> </father>

Summary

The above is all the content about the code of the instance for adding, deleting, modifying, and querying the XML document using DOM in java. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.