Java and XML (1): Using Dom to operate XML files

Source: Internet
Author: User

1. Dom Introduction

Dom is the official W3C standard for XML documents in a way unrelated to the platform and language. Dom is a collection of nodes or information fragments organized by hierarchies. This hierarchy allows developers to search for specific information in the tree. To analyze this structure, you usually need to load the entire document and construct a hierarchy before you can do any work. Because it is based on information layers, Dom is considered to be tree-based or object-based. Dom and tree-based processing in the broad sense have several advantages. First, because the tree is persistent in the memory, you can modify it so that the application can change the data and structure. It can also navigate up and down the tree at any time, rather than one-time processing like sax. Dom is much easier to use.

2. parse XML files using dom

Code example:

Import java. Io. fileinputstream;
Import java. Io. filenotfoundexception;
Import java. Io. ioexception;
Import java. Io. inputstream;

Import javax. xml. parsers. documentbuilder;
Import javax. xml. parsers. documentbuilderfactory;
Import javax. xml. parsers. parserconfigurationexception;

Import org. W3C. Dom. Document;
Import org. W3C. Dom. element;
Import org. W3C. Dom. node;
Import org. W3C. Dom. nodelist;
Import org. xml. Sax. saxexception;

/**
* @ Author: Hu Jiawei
* @ Createtime: 10:12:00
* @ Description: Parse XML files using dom
*/

Public class domxml {

Public void domxml (string filename ){
Try {
Documentbuilder dombuilder = documentbuilderfactory. newinstance (). newdocumentbuilder ();
Inputstream input = new fileinputstream (filename );
Document Doc = dombuilder. parse (input );
Element root = Doc. getdocumentelement ();
Nodelist students = root. getchildnodes ();
If (students! = NULL ){
For (INT I = 0, size = students. getlength (); I <size; I ++ ){
Node student = students. item (I );
If (student. getnodetype () = node. element_node ){
String sexstring = student. getattributes (). getnameditem ("gender"). getnodevalue ();
System. Out. println (sexstring );
}

For (node = student. getfirstchild (); node! = NULL; node = node. getnextsibling ()){
If (node. getnodetype () = node. element_node ){
If (node. getnodename (). Equals ("name ")){
String name = node. getfirstchild (). getnodevalue ();
System. Out. println (name );
}
If (node. getnodename (). Equals ("Age ")){
String age = node. getfirstchild (). getnodevalue ();
System. Out. println (AGE );
}
If (node. getnodename (). Equals ("phone ")){
String Tel = node. getfirstchild (). getnodevalue ();
System. Out. println (TEL );
}
}
}

}
}

} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (parserconfigurationexception e ){
E. printstacktrace ();
} Catch (saxexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}

}

Public static void main (string [] ARGs ){
Domxml xmltest = new domxml ();
String filename = "students. xml ";
Xmltest. domxml (filename );
}

}

Directory structure: place an XML file under the root directory of the project

 
<?xml version="1.0" encoding="UTF-8"?>
<Student roster>
    <Student gender = "male">
        <Name> Li Hua </Name>
        <Age> 14 </age>
        <Phone> 6287555 </phone>
    </Student>
    <Student gender = "male">
        <Name> Zhang San </Name>
        <Age> 16 </age>
        <Phone> 8273425 </phone>
    </Student>
</Student roster>

  

Running result:

Male

Li Hua

14

6287555

Male

Zhang San

16

8273425

3. Use Dom to operate XML files for addition, deletion, query, and modification.

Sample Code:

ImportJava. Io. filenotfoundexception;
ImportJava. Io. fileoutputstream;
ImportJava. Io. ioexception;

ImportJavax. xml. parsers. documentbuilderfactory;
ImportJavax. xml. parsers. parserconfigurationexception;
ImportJavax. xml. Transform. transformer;
ImportJavax. xml. Transform. transformerconfigurationexception;
ImportJavax. xml. Transform. transformerexception;
ImportJavax. xml. Transform. transformerfactory;
ImportJavax. xml. Transform. Dom. domsource;
ImportJavax. xml. Transform. Stream. streamresult;
ImportJavax. xml. XPath. xpathconstants;
ImportJavax. xml. XPath. xpathexpressionexception;
ImportJavax. xml. XPath. xpathfactory;

ImportOrg. W3C. Dom. Document;
ImportOrg. W3C. Dom. element;
ImportOrg. W3C. Dom. node;
ImportOrg. W3C. Dom. nodelist;
ImportOrg. xml. Sax. saxexception;

/**
* @ Author: Hu Jiawei
* @ Createtime: 09:08:03
* @ Description: operate XML files in the Dom, add, query, modify, and delete files.
*/

Public ClassDealxml {

Public Static VoidMain (string [] ARGs ){
Try{
// Document --> node
Document document = documentbuilderfactory. newinstance (). newdocumentbuilder (). parse ("products. xml ");
Element root = Document. getdocumentelement ();

// Add an element node
Element newchild = Document. createelement ("project ");
Newchild. setattribute ("ID", "np001"); // Add the ID attribute

Element nelement = Document. createelement ("name"); // Element Node
Nelement. settextcontent ("new project ");
Newchild. appendchild (nelement );
Element selement = Document. createelement ("START-date ");
Selement. settextcontent ("March 1999 ");
Newchild. appendchild (selement );
Element Eelement = Document. createelement ("end-date ");
Eelement. settextcontent ("Maid 30 2004 ");
Newchild. appendchild (Eelement );

Root. appendchild (newchild );

// Search for an element node
String expression = "/projects/project [3]";
Element Node = (element) selectsinglenode (expression, root); // perform a transformation
// Modify an element node
Node. getattributenode ("ID"). setnodevalue ("new" + node. getattribute ("ID "));
// Root. getelementsbytagname ("project"). Item (2). settextcontent ("");
Expression = "/projects/Project ";
Nodelist = selectnodes (expression, root );
Nodelist. Item (1). getattributes (). getnameditem ("ID"). setnodevalue ("new ID ");
// Delete an element node
Expression = "/projects/project [2]";
Node = (element) selectsinglenode (expression, root );
Root. removechild (root. getfirstchild ());

Output (root, "newprojects. xml ");
}Catch(Saxexception e ){
E. printstacktrace ();
}Catch(Ioexception e ){
E. printstacktrace ();
}Catch(Parserconfigurationexception e ){
E. printstacktrace ();
}
}

Public Static VoidOutput (node, string filename ){
Transformerfactory transfactory = transformerfactory. newinstance ();
Try{
Transformer transformer = transfactory. newtransformer ();
// Set various output attributes
Transformer. setoutputproperty ("encoding", "gb2312 ");
Transformer. setoutputproperty ("indent", "yes ");
Domsource source =NewDomsource ();
// Assign the output node to the holder of the DOM source model (holder)
Source. setnode (node );
Streamresult result =NewStreamresult ();
If(Filename = NULL ){
// Set the standard output stream to the underlying output target of transformer.
Result. setoutputstream (system. Out );
}Else{
Result. setoutputstream (NewFileoutputstream (filename ));
}
// Execute the conversion to output the stream from the source model to the console
Transformer. Transform (source, result );
}Catch(Transformerconfigurationexception e ){
E. printstacktrace ();
}Catch(Transformerexception e ){
E. printstacktrace ();
}Catch(Filenotfoundexception e ){
E. printstacktrace ();
}
}

// Find a separate Node
Private StaticNode selectsinglenode (string expression, object source ){
Try{
Return(Node) xpathfactory. newinstance (). newxpath (). Evaluate (expression, source, xpathconstants. node );
}Catch(Xpathexpressionexception e ){
E. printstacktrace ();
ReturnNULL;
}
}

// Search for all nodes
Private StaticNodelist selectnodes (string expression, object source ){
Try{
Return(Nodelist) xpathfactory. newinstance (). newxpath (). Evaluate (expression, source, xpathconstants. nodeset );
}Catch(Xpathexpressionexception e ){
E. printstacktrace ();
ReturnNULL;
}
}

}

On the left is before modification, on the right is the XML file generated after modification

For more details, see http://www.cnblogs.com/stephen-liu74/archive/2011/09/12/2151209.html

 

Publish via wiz

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.