Access the network file, parse it, and then save

Source: Internet
Author: User

First build the Student.xml file under the Tomcat server and note the location of the file

Student.xml content is:

<?xml version= "1.0" encoding= "UTF-8"?><students><student><ID>0001</ID><name>Xiao ming</name><class>Class One</class></student><student><ID>0002</ID><name>Little Red</name><class>Class Two</class></student><student><ID>0003</ID><name>Jack bauer</name><class>Class Three</class></student></Students>`
Write the Parsexml.java class to parse it and save
ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileWriter;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.net.URL;ImportJava.net.HttpURLConnection;ImportJava.util.logging.Level;ImportJava.util.logging.Logger;ImportJavax.xml.parsers.DocumentBuilder;ImportJavax.xml.parsers.DocumentBuilderFactory;ImportOrg.w3c.dom.Document;ImportOrg.w3c.dom.Element;ImportOrg.w3c.dom.NodeList;/** * * @author Xiao Song * * Public  class prasexml {     Public Static void Main(string[] args) {//parsing XML files in a network I was visiting the local service.String Afterprasefromxml = Prasexml ("Http://localhost:8080/firsrt/student.xml");//Save the parsed results in a file        BooleanFlag = SaveXML (Afterprasefromxml,"D://a.txt"); System.out.println ("saved successfully"+ flag); }/** * Parse XML * * @param path * @return  */     Public StaticStringPrasexml(String Path) {StringBuffer SB =NULL; InputStream ism =NULL; HttpURLConnection connection =NULL; URL url =NULL;Try{URL =NewURL (path); Connection = (httpurlconnection) url.openconnection ();//Access ConnectISM = Connection.getinputstream ();//BufferedReader reader=new BufferedReader (New InputStreamReader (ISM));//StringBuffer sb=new stringbuffer ();//String line=null;//while ((Line=reader.readline ())!=null) {//Sb.append (line);//            }Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();            Documentbuilder db = Dbf.newdocumentbuilder ();            Document d = db.parse (ISM); Element element = D.getdocumentelement ();//Get the sub-nodes under students, i.e. studentNodeList list = Element.getchildnodes (); SB =NewStringBuffer (); for(inti =0; I < list.getlength (); i++) {NodeList nodes = List.item (i). Getchildnodes ();//Get sub-nodes under student                 for(intj =0; J < Nodes.getlength (); J + +) {if(Nodes.item (j). Gettextcontent ()! ="") {Sb.append (Nodes.item (j). Gettextcontent ());//Save the parsed content in SB-image}                }            }//Element element= d.getdocumentelement ();//Node node= element.getattributenode ("name");//System.out.println (Node.getnodename ());}Catch(Exception ex)        {Ex.printstacktrace (); }finally{Try{if(ISM! =NULL) {ism.close (); ISM =NULL; }if(Connection! =NULL) {connection.connect (); Connection =NULL; }            }Catch(IOException ex) {Logger.getlogger (PraseXml.class.getName ()). log (Level.severe,NULL, ex); }        }returnSb.tostring (). Trim (); }/** * Save to File * * @param contentstring * @param filePath * @return * /     Public Static Boolean SaveXML(String contentstring, String filePath) {File File =NewFile (FilePath); BufferedWriter out =NULL;Try{if(File.exists ())            {File.delete ();            } file.createnewfile (); out =NewBufferedWriter (NewFileWriter (file)); Out.write (Contentstring,0, Contentstring.length ()-1);return true; }Catch(Exception ex) {Logger.getlogger (PraseXml.class.getName ()). log (Level.severe,NULL, ex); }finally{if(Out! =NULL) {Try{Out.close (); out =NULL; }Catch(IOException ex) {Logger.getlogger (PraseXml.class.getName ()). log (Level.severe,NULL, ex); }            }        }return false; }}
With the Tomcat server open, you can compile and run.

The end of the final, the teacher told me each of the questions, I am out of two questions. And I think of a problem is to access the network files, and then parse, save. The knowledge points used to httpurlconnection this class, the returned data I go to parse it, and then write to the file. Also some basic IO operations ... To the HTTP protocol in my understanding is that we request to the server, and then the server response data to you, such as we open in the browser http://www.baidu.com actually we are requesting Baidu server, and then Baidu Server returned is HTML, our browser to parse it, just display the interface.

Access the network file, parse it, and then save

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.