We know that the XML file can be used for data transmission, or with a DTD constraint file as a configuration file, of course, its essence is a tag and a lot of space to maintain the format of the string, then you can use Java operation. This example is done on the basis of the jar package to be used with myeclipse into the dom4j resolution, and of course dom4j is self-evident with respect to the ease of parsing such as dom sax . The following is the use case XML file <?xml version= "1.0" encoding= "UTF-8"? ><persons> <person age= " weight=" gender= "FEMAIL" > <name> Xiao Ming </name > <gender>mail</gender> Here we use Java for the XML file operation, the code is as follows:
package test_xml;import java.util.iterator;import java.util.list;import org.dom4j.attribute;import org.dom4j.document;import org.dom4j.documenthelper;import Org.dom4j.element;import org.dom4j.entity;import org.dom4j.node;import utils. Xmlutils;public class mydemo1 {public static void main (String[] args) Throws exception{ //The following methods are described, The reader may choose//getfirsttext ();//getsecondtext ();//insertelement ();//insertattrandele ();//deletesubelement ();// Updateelement ();//insertattr ();//updateattr ();//deleteattr ();//getallnamenode ();//getallnamenode ();// Getsecondpersonattr ();//getrootnodeattr ();//getsecongelelmentattr ();} /** * get all attribute values for the second person and output to the console * @throws exception */private static void getsecongelelmentattr () throws Exception {Document dom = Xmlutils.getdocument ("PersOns.xml "); Element root = dom.getrootelement (); List<element> list = root.elements (); Element element = list.get (0); for (iterator<attribute> i = Element.attributeiterator (); I.hasnext ();) {attribute next = i.next ();// Note that this needs to be added to the paradigm to ensure that it is a attribute object and then call its GetValue () method to output the desired value System.out.println (Next.getvalue ());}} /** * query all age attributes and traverse output * @throws Exception */private static void Getrootnodeattr () throws exception {document dom = xmlutils.getdocument (" Persons.xml "); Element root = dom.getrootelement (); List<element> list = root.elements (); for (iterator i = root.elementiterator ("person"), I.hasnext ();) {element element = (Element) i.next (); String attributevalue = element.attributevalue ("Age"); System.out.println (AttributeValue);}} /** * gets the gender element of the second person and outputs its contents &NBSP;*&NBSP; @throws exception */private static void getsecondpersonattr () throws Exception {document dom = xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement (); List<element>list = root.elements (); Element gender = list.get (1). Element ("gender"); System.out.println (Gender.gettext ());} /** * Gets the name child node under all the person nodes and traverses the output to the console * @throws exception */private static void getallnamenode () throws Exception {Document dom = Xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement (); List<element>selectnodes = root.selectnodes ("//name"); for ( Iterator i = root.elementiterator (); i.hasnext (); ) { Element element = (Element) i.next (); &Nbsp; system.out.println (element.element ("name"). GetName ()); }}/** * traverse the output of all person nodes and output to the console * @throws exception */private static void getallpersonnode () throws exception {document dom = xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement (); List selectnodes = root.selectnodes ("//name"); for ( Iterator i = root.elementiterator (); i.hasnext (); ) { Element element = (Element) i.next (); system.out.println (Element.getname ()); }}/** * get a third person's weight attribute and delete * @throws exception */Private static void deleteattr () throws exception {document dom = xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement (); List<element> list = root.elements (); Element secondperson = list.get (1); Attribute attribute = secondperson.attribute ("weight"); if (attribute == null) { System.out.println ("false! not exsit ");} Attribute.getparent (). Remove (attribute); Xmlutils.writertoxml (dom, "Persons.xml"); System.out.println ("~~~~~~~~~~delete attribute successfully!~~~~~~~~~~~");} /** * Update the Age attribute of the first person and output the values before and after the update to the console * @throws Exception */private static Void updateattr () throws exception {document dom =xmlutils.getdocument (" Persons.xml "); Element root = dom.getrootelement (); Attribute age = root.element ("person"). Attribute ("Age"); System.out.println ("beforE updating: "+age.getvalue ()"); Age.settext ("30"); Xmlutils.writertoxml (dom, "Persons.xml"); System.out.println ("behind updating:" +age.getvalue ()); System.out.println ("************update successfully!***********");} /** * add an attribute to the first person gender the value is femail * @throws exception */private static void insertattr () throws Exception {Document dom = Xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement (); Root.element ("person"). AddAttribute ("Gender", "FEMAIL" ); Xmlutils.writertoxml (dom, "Persons.xml"); System.out.println ("+++++++++add attribute successfully!++++++++");} /** * get first person's name tag and modify * @throws Exception */private static void Updateelement () throws exception {document dom =xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement ();//1. Get the first person 2. Change the value of its Name property element firstperson = root.element ("person"); Firstperson.element ("name"). SetText ("WXM!!!!"); /Cut the score clearly that is the root tag that is the label that needs to be modified Xmlutils.writertoxml (dom, "Persons.xml"); System.out.println ("=========update successfully!============");} /** * Delete a third person's gender tags * @throws Exception */private static void Deletesubelement () throws exception {document dom = xmlutils.getdocument (" Persons.xml "); Element root = dom.getrootelement ();//1. Get a third person 2. Get the gender node of the third person and delete list< Element> list = root.elements (); Element gender = list.get (2). Element ("gender"); Gender.getparent (). Remove (gender);// Xmlutils.writertoxml (dom, "Persons.xml") can only be removed through the parent tag; System.out.println ("=======delete successfully=======");} /** * to the height of the second person insert a hobby element in front of it and add a nationality attribute to this attribute * @throws Exception */private Static void insertattrandele () throws exception {document dom = xmlutils.getdocument ("Persons.xml"); Element root = dom.getrootelement ();//1. Create a hobby node 2. Get the second book and plug the Well node in front of its height node element Favorite = documenthelper.createelement ("favorite"). AddAttribute ("nationality", "China"); Favorite.settext ("Running"); List<element> listpersons = root.elements (); element person = (Element) listpersons.get (1); List listperson = person.elements (); Listperson.add (1,favorite ); Xmlutils.writertoxml (dom, "Persons.xml"); System.out.println ("=========insert sucessfully!========");} /** * Add a height node to the first person * @throws Exception */private static void Insertelement () throws exception {document dom = xmlutils.getdocument (" Persons.xml "); Element root = dom.getrootelement ();//1. Create a node 2. Get the first person attach the created node to the first person on element hight = D ocumenthelper.createelement ("hight"); Hight.settext ("185"); Root.element ("person"). Add (hight); Xmlutils.writertoxml (dom, "Persons.xml"); System.out.println ("=========add successfully=========");} /** * Query the gender of the second person and output to the console * @throws exception */private static void getsecondtext () throws exception {document dom = xmlutils.getdocument (" Persons.xml "); Element root = dom.getrootelement (); List<element> list = root.elements (); Element secondelement = list.get (1). Element ("gender"); System.out.println (Secondelement.gettext ());} /** * get the first person's name attribute and print it to the console * @throws exception */private static void getfirsttext () throws exception {document dom = xmlutils.getdocument (" Persons.xml "); Element root = dom.getrootelement (); Element person = root.element ("person"). Element ("name")); System.out.println (Person.gettexttrim ());}} //of course, each time you want to create a new dom4j XML file parser, we can take out to do a tool class and then use it to facilitate the code as follows: package com.buu;import java.io.File;import java.io.FileNotFoundException;import java.io.fileoutputstream;import java.io.outputstream;import org.dom4j.document;import org.dom4j.io.outputformat;import org.dom4j.io.saxreader;import org.dom4j.io.xmlwriter;public class utilsforxml {/** * needs a way to create the dom4j de xml parser and return a Document object */public Static document getdocument (String xmlpath) throws Exception {SAXReader Reader = new saxreader ();//pass the XML file path to the Document object and return to the example domdocument dom = Reader.read (New file (Xmlpath)); return dom;} /** * requires a method to write the updated Document object to an XML file * @throws Exception */public Static void writetoxml (Document dom&nbsP;,string xmlpath) throws exception{//first create the style and output stream outputformat format = new OutputFormat (). Createprettyprint (); Outputstream out = new fileoutputstream (XmlPath); Xmlwriter writer = new xmlwriter (Out,format);//Close Stream Writer.write (DOM) after write; Writer.close ();}} //above is the use of dom4j parsing methods to manipulate XML files, and so on, we can use the XML file model//quasi-database for data deletion and modification operation The specific code is as follows: package com.buu;import java.util.scanner;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.Node;public class Manager {public static void main (String[] args) throws exception{//1. Accept user input information//2. Gets the user input information//3. To determine and process the request while (true) {System.out.println ("please input your choice! "); System.out.println ("1.add 2.query 3.delete"); Scanner input = new&nbSp Scanner (system.in); String type = input.nextline (); if ("1". Equals (type)) {person person = new Person ();//The input information is saved to the person object System.out.println ("Please input your name:"); String name = input.nextline ();p erson.setname (name); System.out.println ("Please input your gender:"); String gender = input.nextline ();p erson.setgender (gender); System.out.println ("Please input your age:"); String age = input.nextline ();p erson.setage (age); System.out.println ("Please input your weight:"); String weight = input.nextline ();p erson.setweight (weight), add (person); System.out.println ("=========add successfully!==========");} Else if ("2". Equals (Type)) {System.out.println ("please input age:"); String age = input.nextline (); if (age==null) {return;} String queryperson = query (age); SYSTEM.OUT.PRINTLN ("* * *" +queryperson+ "* * *"); SysTem.out.println ();} Else if ("3". Equals (Type)) {System.out.println ("please input weight"); String weight = input.nextline (); if (weight==null) {System.out.println ("please input Again! ");} Delete (weight); System.out.println ("" ' "'" ' delete successfully ' ");} Else{system.out.println (" false! please check !");}}} Private static void delete (string weight) throws Exception {Document Dom = utilsforxml.getdocument ("Persons.xml"); Element root = dom.getrootelement (); element bedelete = (Element) root.selectsinglenode ("//person[@weight =" +weight+ "]"); if (bedelete == null) {System.out.println ("not exist!");} Bedelete.getparent (). Remove (Bedelete); Utilsforxml.writetoxml (dom, "Persons.xml");} Private static string query (string age) throws exception {document dom = utilsforxml.getdocument ("Persons.xml"); Element root = dom.getrootelement (); element bequery = (Element) root.selectsinglenode ("//person[@age =" +age+ "]"); if (bequery == null) {System.out.println ("not exist!");} Person person = new person ();p erson.setname (Bequery.elementtext ("name"));p Erson.setweight ( Bequery.attributevalue ("Weight"));p Erson.setage (Bequery.attributevalue ("Age"));p Erson.setgender ( Bequery.elementtext ("gender")); return person.tostring ();} Private static void add (Person person) throws exception {document dom = utilsforxml.getdocument ("Persons.xml"); Element root = dom.getrootelement ();//Note this is just getting the root element, but there are no elements underneath it, you need to add the element personelement manually = root.addelement ("person"). AddAttribute ("Age", person.getage ()). AddAttribute ("Weight", Person.getweight ());p ersonelement.addelement ("name"). SetText (Person.getname ());p ersonelement.addelement (" Gender "). SetText (Person.getgender ());Writes the updated Document object to the XML file to Utilsforxml.writetoxml (dom, "Persons.xml");}} //Summary: XML file is not just a data format, but also a kind of application scenario
This article is from the "10891776" blog, please be sure to keep this source http://10901776.blog.51cto.com/10891776/1735150
Java-based XML file simulation database for pruning and checking operations