XML is an Extensible Markup language
The following is a complete XML file (also a sample of read-write XML, as described below):
<?XML version= "1.0" encoding= "UTF-8"?
><poem author= "William Carlos Williams" title= "the great figure" ><line>among the rain</line>< Line>and Ligths</line><line>i saw the figure 5</line><line>in Gold</line><line >on a Red</line><line>fire truck</line><line>moving</line><line>tense</ Line><line>unheeded</line><line>to Gong Clangs</line><line>siren howls</line ><line>and wheels Rumbling</line><line>through The Dark city</line></poem>
First, Write XML
This article describes two ways to use the DOM development package to write XML files and to use String objects in a way that
Use the poem class as a data source to provide the content that needs to be translated into XML:
Class Poem {private static string title = "The Great figure";p rivate static string author = "William Carlos Williams";p Riv Ate static arraylist<string> lines = new arraylist<string> (), Static {Lines.add ("Among the Rain"), Lines.add ( "and Ligths"); Lines.add ("I saw the Figure 5"), Lines.add ("in Gold"), Lines.add ("on a Red"), Lines.add ("Fire Truck"); Lines.add ("moving"); Lines.add ("tense"); Lines.add ("unheeded"); Lines.add ("To Gong clangs"); Lines.add ("Siren howls") ; Lines.add ("and Wheels rumbling"); Lines.add ("Through the Dark City"); public static String GetTitle () {return title;} public static String Getauthor () {return author;} public static arraylist<string> Getlines () {return lines;}}
1. write XML files in Dom
Process:
(1) Create an empty Document object (the topmost DOM object, including everything else needed to create the XML).
(2) Create elements and attributes to add elements and attributes to the document object.
(3) Convert the contents of the document object into a string object.
(4) Write the string object to the target file.
Import Java.util.arraylist;import java.io.*;import Javax.xml.parsers.*;import Javax.xml.transform.*;import Javax.xml.transform.dom.domsource;import javax.xml.transform.stream.streamresult;import org.w3c.dom.*;p ublic Class XmlTest {public static void main (string[] args) {Document doc = createXMLContent1 ();//Create an empty document Createelements (DOC); Create xmlstring xmlcontent = createxmlstring (doc);//create String to represent XMLwriteXMLToFile1 (xmlcontent);} /*********** writes an XML file with the DOM ***********/private static document CreateXMLContent1 () {Document doc = Null;try {///enables an application to Document gets the parser that generates the DOM object tree documentbuilderfactory DBFAC = documentbuilderfactory.newinstance ();D Ocumentbuilder DocBuilder = Dbfac.newdocumentbuilder ();d oc = Docbuilder.newdocument ();//Specifies whether this document is a separate property as part of the XML declaration.When not specified, this property is false. Doc.setxmlstandalone (TRUE);} catch (parserconfigurationexception PCE) {System.out.println ("couldn ' t create a documentbuilder"); System.exit (1);} return doc;} private static void Createelements (Document doc) {//create root element poem = doc.createelement ("poem");p Oem.setattribute (" Title ", Poem.gettitle ());p Oem.setattribute (" Author ", Poem.getauthor ());//Add the root element to the document Doc.appendchild (POEM);// Create a child element for (String LineIn:Poem.getLines ()) {Element line = doc.createelement ("line"); Text Linetext = Doc.createtextnode (LineIn); Line.appendchild (linetext);//Add each element to the root element poem.appendchild (line);}} private static string createxmlstring (Document doc) {//convert DOM to string transformer transformer = NULL; StringWriter StringWriter = new StringWriter (); try {transformerfactory transformerfactory = Transformerfactory.newinstance (); transformer = Transformerfactory.newtransformer ();//Whether the XML should be output Statement Transformer.setoutputproperty (outputkeys.omit_xml_declaration, "yes");// Do you want to wrap your own transformer.setoutputproperty (Ou) in XML format?Tputkeys.indent, "yes");//Create a string to include Xmlstringwriter = new StringWriter (); Streamresult result = new Streamresult (stringwriter);//The holder of the conversion result domsource Source = new Domsource (DOC); Transformer.transform (source, result);} catch (Transformerconfigurationexception e) {System.out.println ("couldn ' t create a Transformer"); System.exit (1);} catch (Transformerexception e) {System.out.println ("couldn ' t transforme DOM to a String"); System.exit (1);} return stringwriter.tostring ();} private static void WriteXMLToFile1 (String xmlcontent) {string fileName = "E:\\test\\domoutput.xml"; try {File domoutput = New File (FileName); FileOutputStream Domoutputstream = new FileOutputStream (domoutput);d Omoutputstream.write (XmlContent.getBytes ()); Domoutputstream.close (); System.out.println (FileName + "was successfully written");} catch (FileNotFoundException e) {System.out.println ("couldn ' t find a file called" + fileName); System.exit (1);} catch (IOException e) {System.out.println ("couldn ' t write a file called" + FileName); System.exit (1);}}
2. write XML file with string
Such a method is relatively simple. is to simply use the string to describe the entire XML file, and then save the file.
Second, read the XML file
Two ways: Read the XML file with the DOM and use the Sax method. The general DOM handles XML files that are smaller in content. Sax can handle arbitrary-sized XML files.
1. reading XML files with Dom
public class XmlTest {public static void main (string[] args) {String fileName = "E:\\test\\domoutput.xml"; writefileconten Tstoconsole (fileName);} /*********** reading XML file with Dom ***********/private static void Writefilecontentstoconsole (String fileName) {Document doc = CreateDocument (FileName); Element root = Doc.getdocumentelement ();//Gets the root element StringBuilder sb = new StringBuilder (); Sb.append ("The root element is name D:\ "" + root.getnodename () + "\" "); Sb.append (" and has the following attributes: "); NamedNodeMap attributes = Root.getattributes (); for (int i = 0; i < attributes.getlength (); i++) {Node Thisattribute = a Ttributes.item (i); Sb.append (Thisattribute.getnodename ()); Sb.append ("(\" "+ thisattribute.getnodevalue () +" \ ")"); if (I < Attributes.getlength ()-1) {Sb.append (",");}} System.out.println (SB);//description information of the root element nodelist nodes = Doc.getelementsbytagname ("line"), for (int i = 0; i < Nodes.getlen Gth (); i++) {Element element = (Element) nodes.item (i); System.out.println ("Found an element" nameD \ "" + element.gettagname () + "\" "+" with the following content: \ "" + element.gettextcontent () + "\" ");}} private static document CreateDocument (String fileName) {//Document object to create Dom from file document doc = null;try {file XMLFile = new File (fileName);D ocumentbuilderfactory DBFAC = documentbuilderfactory.newinstance ();D Ocumentbuilder Docbuilder = Dbfac.newdocumentbuilder ();d oc = Docbuilder.parse (xmlfile);//parse XML file loaded into DOM document Doc.setxmlstandalone (TRUE);} catch (IOException e) {e.printstacktrace ();} catch (Saxexception e) {e.printstacktrace ();} catch ( Parserconfigurationexception e) {e.printstacktrace ();} return doc;}} /* Output: * The root element is named: ' Poem ' and has the following Attributes:author ("William Carlos Williams"), title ("The Great Figure") * Found an element named ' line ' with the following content: ' Among the Rain ' * Found an element named "Line" with the following content: "and ligths" * ... *///: ~
2. reading XML files with sax
Sax uses the ContentHandler interface to expose parsing events, and the SAX package provides a default implementation class DefaultHandler, whose default behavior is to do nothing. Here are some of the methods that are covered by the Xmltoconsolehandler class to capture the contents of an XML file.
Import Org.w3c.dom.characterdata;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;public Class XmlTest {public static void main (string[] args) {String fileName = "E:\\test\\domoutput.xml"; Getfilecontents ( FileName);} private static void Getfilecontents (String fileName) {try {Xmltoconsolehandler handler = new Xmltoconsolehandler (); SAXParserFactory factory = Saxparserfactory.newinstance (); SAXParser saxparser = Factory.newsaxparser (); Saxparser.parse (FileName, handler);} catch (IOException e) {e.printstacktrace ();} catch (Parserconfigurationexception e) {e.printstacktrace ();} catch ( Saxexception e) {e.printstacktrace ();}}} /*********** reading XML files with Sax ***********/class Xmltoconsolehandler extends DefaultHandler {public void characters (char[] Content, int start, int length) throws Saxexception {//handles the real content of the element System.out.println ("Found content:" + new String (Conten T, start, length));} public void EndElement (string arg0, String localname, String qName) throws Saxexception{System.out.println ("Found the end of an element named \" "+ QName +" \ "");} public void Startelement (string uri, String localname, String Qname,attributes Attributes) throws Saxexception {Stringbui Lder sb = new StringBuilder () sb.append ("Found the start of an element named \" "+ QName +" \ ""); if (attributes! = NULL &A mp;& attributes.getlength () > 0) {sb.append ("with attributes named"), for (int i = 0; I < attributes.getlength (); i++) {String AttributeName = attributes.getlocalname (i); String AttributeValue = Attributes.getvalue (i); Sb.append ("\" "+ AttributeName +" \ ""); Sb.append ("(value ="); Sb.append ( "\" "+ AttributeValue +" \ ""); Sb.append (")"); if (I < Attributes.getlength ()-1) {Sb.append (",");}}} System.out.println (Sb.tostring ());}}
Java Learning notes--read and write XML