Read and write XML files in Java

Source: Internet
Author: User

To read an XML file:

 Public Static voidgetfamilymemebers () {documentbuilderfactory dbf=documentbuilderfactory.newinstance (); Dbf.setignoringelementcontentwhitespace (true); Try{Documentbuilder db=Dbf.newdocumentbuilder (); Document Doc= Db.parse (Xmlpath);//parsing an XML file using the DOMNodeList sonlist= Doc.getelementsbytagname ("Son");  for(inti = 0; I < sonlist.getlength (); i++)//Looping Objects{Element son=(Element) Sonlist.item (i);  for(Node node = son.getfirstchild (); Node! =NULL; node =node.getnextsibling ()) {                      if(Node.getnodetype () = =Node.element_node) {String name=Node.getnodename (); String value=node.getfirstchild (). Getnodevalue (); SYSTEM.OUT.PRINTLN (Name+" : "+value); }                  }              }        } Catch(Exception e) {e.printstacktrace (); }    }

Note that factory can generate Builder,builder can be generated document,document each node in a node composed of nodelist,nodelist can generate a specific name can be converted into element, element can return a node in the form of a son, node form of elements can get its properties.

Now if you want to parse the following XML:

<?  ?><Root><Left= "100"  Top= "a"> Daily report </Header>< /Root>

You can use the code:

ImportJava.io.File;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;Importorg.w3c.dom.NodeList; Public classXml { Public Static voidMain (string[] args) {Try{documentbuilderfactory Factory=documentbuilderfactory. newinstance (); Documentbuilder Builder=Factory.newdocumentbuilder (); Document Document= Builder.parse (NewFile ("File.xml")); Element rootelement=document.getdocumentelement (); NodeList List= Rootelement.getelementsbytagname ("Header"); Element element= (Element) list.item (0); System.out.println (Element.getchildnodes (). Item (0). Getnodevalue ()); } Catch(Exception e) {System.out.println ("Exception:" +e.getmessage ()); } }}

Write an XML file

 Public Static voidCreateson () {documentbuilderfactory dbf=documentbuilderfactory.newinstance (); Dbf.setignoringelementcontentwhitespace (false); Try{Documentbuilder db=Dbf.newdocumentbuilder (); Document xmldoc=Db.parse (Xmlpath); Element Root=xmldoc.getdocumentelement (); //Delete the specified nodeElement son=xmldoc.createelement ("Son"); Son.setattribute ("id", "004"); Element name= Xmldoc.createelement ("name"); Name.settextcontent (Youngest son);            Son.appendchild (name); Element Age= Xmldoc.createelement ("name"); Age.settextcontent ("0");                        Son.appendchild (age);            Root.appendchild (son); //SaveTransformerfactory factory =transformerfactory.newinstance (); Transformer former=Factory.newtransformer (); Former.transform (NewDomsource (xmldoc),NewStreamresult (NewFile (Xmlpath)); }Catch(Exception e) {e.printstacktrace (); }    }

Read and write XML files in Java

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.