Java Parse XML files, add nodes, and delete operations

Source: Internet
Author: User

1. java code:
Mainly uses dom for operations
Copy codeThe Code is as follows:
Package test;
Import java. io. IOException;
Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;
Import javax. xml. parsers. ParserConfigurationException;
Import javax. xml. transform. Transformer;
Import javax. xml. transform. TransformerConfigurationException;
Import javax. xml. transform. TransformerException;
Import javax. xml. transform. TransformerFactory;
Import javax. xml. transform. dom. DOMSource;
Import javax. xml. transform. stream. StreamResult;
Import org. w3c. dom. Document;
Import org. w3c. dom. Element;
Import org. w3c. dom. NodeList;
Import org. w3c. dom. Text;
Import org. xml. sax. SAXException;
Public class XmlOprate {
Document doc;
DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance ();
DocumentBuilder builder;
NodeList imags;
String path;
Public NodeList getImags (){
Return imags;
}
Public void setImags (NodeList imags ){
This. imags = imags;
}
/**
* Constructor
* @ Param path: path of the xml file
* @ Param nodes: name of the xml node to be parsed
*/
Public XmlOprate (String path ){
Super ();
This. path = path;
System. out. println (System. getProperty ("user. dir "));
}
/**
* Parse XML
* @ Param path
*/
Public void readXml (){
Try {
Builder = factory. newDocumentBuilder ();
Document doc = builder. parse (path );
Doc. normalize ();
NodeList imags = doc. getElementsByTagName ("imags ");
This. setImags (imags );
For (int I = 0; I <imags. getLength (); I ++ ){
Element link = (Element) imags. item (I );
System. out. print ("title :");
System. out. println (link. getElementsByTagName ("title"). item (0). getFirstChild (). getNodeValue ());
System. out. print ("URL :");
System. out. println (link. getElementsByTagName ("url"). item (0). getFirstChild (). getNodeValue ());
System. out. print ("imgsrc :");
System. out. println (link. getElementsByTagName ("imgsrc"). item (0). getFirstChild (). getNodeValue ());
System. out. println ();
}
} Catch (ParserConfigurationException e ){
E. printStackTrace ();
} Catch (SAXException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
/**
* AddCode
* @ Param path
*/
Public void addXmlCode (String imgsrc, String title, String url ){
Try {
Builder = factory. newDocumentBuilder ();
Document doc = builder. parse (path );
Doc. normalize ();
Text textseg;
Element imag = doc. createElement ("imags ");
Element linkimgsrc = doc. createElement ("imgsrc ");
Textseg = doc. createTextNode (imgsrc );
Linkimgsrc. appendChild (textseg );
Imag. appendChild (linkimgsrc );
Element linktitle = doc. createElement ("title ");
Textseg = doc. createTextNode (title );
Linktitle. appendChild (textseg );
Imag. appendChild (linktitle );
Element linkurl = doc. createElement ("url ");
Textseg = doc. createTextNode (url );
Linkurl. appendChild (textseg );
Imag. appendChild (linkurl );
Doc. getDocumentElement (). appendChild (imag );
TransformerFactory tFactory = TransformerFactory. newInstance ();
Transformer transformer;
Transformer = tFactory. newTransformer ();
DOMSource source = new DOMSource (doc );
StreamResult result = new StreamResult (new java. io. File (path ));
Transformer. transform (source, result );
} Catch (Exception e ){
}
}
/**
* Delete xml code
* @ Param path
*/
Public void delXmlCode (){
Try {
Builder = factory. newDocumentBuilder ();
Doc = builder. parse (path );
Doc. normalize ();
NodeList imags = doc. getElementsByTagName ("imags ");
Element elink = (Element) imags. item (0 );
Elink. removeChild (elink. getElementsByTagName ("imgsrc"). item (0 ));
Elink. removeChild (elink. getElementsByTagName ("title"). item (0 ));
Elink. removeChild (elink. getElementsByTagName ("url"). item (0 ));
Doc. getFirstChild (). removeChild (elink );
TransformerFactory tFactory = TransformerFactory. newInstance ();
Transformer transformer = tFactory. newTransformer ();
DOMSource source = new DOMSource (doc );
StreamResult result = new StreamResult (new java. io. File (path ));
Transformer. transform (source, result );
} Catch (ParserConfigurationException e ){
E. printStackTrace ();
} Catch (SAXException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
} Catch (TransformerConfigurationException e ){
E. printStackTrace ();
} Catch (TransformerException e ){
E. printStackTrace ();
}
}
}

2. xml section
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Root>
<Imags>
images/ad-01.jpg </imgsrc>
<Title> Ho Chi Minh City </title>
<Url> http://torchrelay.beijing2008.cn/cn/journey/hochiminhcity/ </url>
</Imags>
<Imags>
images/ad-02.jpg </imgsrc>
<Title> Hong Kong 2 </title>
<Url> http://torchrelay.beijing2008.cn/cn/journey/hongkong/ </url>
</Imags>
</Root>

3. Summary:
The three methods for xml operations (read, write, and delete) have the same initialization statement:
Copy codeThe Code is as follows:
Builder = factory. newDocumentBuilder ();
Document doc = builder. parse (path );
Doc. normalize ();

At first, I plan to write the same part in the constructor, but in the test, it is found that the NULL pointer error will always be reported (it took me a long time );
Instead
Builder = factory. newDocumentBuilder ();
When it is placed in the builder's initialization statement, the reading is okay, but an error is returned when writing or deleting the statement;
So I wrote it like this now. It seems a bit messy, but I didn't expect any good method. I posted it here first, and it may be used later.

Related Article

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.