Use DOM/JDOM to parse XML files (3)

Source: Internet
Author: User
Tags xsl xsl file xslt

I almost gave up, but I still can't forget it. I finally logged on again.
Every time in the dead of night, every time you are alone and helpless, every time you are full of worries, except my blog, who else will listen to me?
I am not sleeping at night, my blog is not sleeping with me, I am not sleeping, my blog is not sleeping with me ......

I have previously recorded two self-written posts for reading and writing XML files. It is not perfect. It is only suitable for simple applications and cannot complete more complex and advanced functions. Recently it is easy to use a more elegant one, and then record it for future reference.
More and more people prefer to use the word "Elegance" to describe a piece of good code. There is no good reason, but it feels quite good. Do I need a reason to like a word? Do I need a reason to like something? Do I need a reason to like a person ?......

Import java. Io. file;
Import java. Io. filewriter;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. outputstream;
Import java. util. List;

Import org. JDOM. Document;
Import org. JDOM. element;
Import org. JDOM. Input. saxbuilder;
Import org. JDOM. Output. format;
Import org. JDOM. Output. xmloutputter;
Import org. JDOM. XPath. XPath;

/**
* Parse XML using JDOM
*
* @ Filename: xmlutil. Java
* @ Author javer. Leo (QQ: 84831612)
* @ Date 2006-8-16
*/
Public final class xmlutil
{
/**
* Define the XML encoding method
*/
Public static final string encode_gbk = "GBK ";
Public static final string encode_utf8 = "UTF-8 ";
Public static final string encode_utf16 = "UTF-16 ";
Public static final string encode_gb2312 = "gb2312 ";
Public static final string encode_iso8859 = "ISO8859-1 ";

Private Static format = format. getprettyformat ();

Static {
Format. setencoding (encode_utf8 );
}

/**
* Read and parse an XML document from the file at XML/sample. xml.
* This method corresponds to the Code in listing 7.
* @ Param filepath: Path of the XML file to be parsed
* @ Return the JDOM document parsed from the file.
* @ Throws ioexception
*/
Public static document readdocument (string filepath) throws ioexception {
Try {
Saxbuilder builder = new saxbuilder (false );
Document anotherdocument = builder. Build (new file (filepath ));
Return anotherdocument;
} Catch (exception e ){
E. printstacktrace ();
Throw new ioexception (E. getmessage ());
}
}

/**
* Read and parse an XML document from the file at XML/sample. xml.
* This method corresponds to the Code in listing 7.
* @ Param filepath: Path of the XML file to be parsed
* @ Return the JDOM document parsed from the file.
* @ Throws ioexception
*/
Public static document readdocument (inputstream input) throws ioexception {
Try {
Saxbuilder builder = new saxbuilder (false );
Document anotherdocument = builder. Build (input );
Input. Close ();
Return anotherdocument;
} Catch (exception e ){
Throw new ioexception (E. getmessage ());
}
}

/**
* Reading XML files
* @ Param srcfile target file
* @ Return DOM object
* @ Throws ioexception
*/
Public static document readdocument (File srcfile) throws ioexception {
Try {
Saxbuilder builder = new saxbuilder ();
Document anotherdocument = builder. Build (srcfile );
Return anotherdocument;
} Catch (exception e ){
Throw new ioexception (E. getmessage ());
}
}

/**
* Add the element with the specified Element Identification name to the specified document model.
* @ Param document the document model of the element to be added
* @ Param elementname the name of the element to be added
* @ Param parentelementpath parent element path
* @ Return
*/
Public static void addelement (Object document, string parentelementpath, string elementname ){
Try {
Element parentelement;
Parentelement = (element) XPath. selectsinglenode (document, parentelementpath );
Element newelement = new element (elementname );
Parentelement. addcontent (newelement );
} Catch (exception E1 ){
E1.printstacktrace ();
}
}

/**
* Add the created element to the specified document model.
* @ Param document the document model of the element to be added
* @ Param newelement the new element to be added
* @ Param parentelementpath parent element path
* @ Return
*/
Public static void addelement (Object document, string parentelementpath, element newelement ){
Try {
Element parentelement;
Parentelement = (element) XPath. selectsinglenode (document, parentelementpath );
Parentelement. addcontent (newelement );
} Catch (exception E1 ){
E1.printstacktrace ();
}
}

/**
* Obtain the list of child elements in the path of the specified child element
* @ Param document the JDOM document built from listing 2
* @ Param visitednodename: Specifies the name of the child node element to be accessed.
* @ Return returns the list of child elements in the specified Element path.
*/
Public static list getchildrenelement (Object document, string visitednodename ){
List visitelements = NULL;
Try {
Visitelements = XPath. selectnodes (document, visitednodename );
} Catch (exception e ){
E. printstacktrace ();
}
Return visitelements;
}

/**
* Obtain the path name and attribute name and value of the specified child element.
* @ Param document the JDOM document built from listing 2
* @ Param visitednodename: Specifies the name of the child node element to be accessed.
* @ Param attributename attribute name
* @ Param attributevalue Attribute Value
* @ Return returns the specified element.
*/
Public static element getchildelement (Object document, string visitednodename, string attributename, string attributevalue ){
Element visitelement = NULL;
Try {
Visitelement = (element) XPath. selectsinglenode (document, visitednodename + "[@" + attributename + "= '" + attributevalue + "']");
} Catch (exception e ){
E. printstacktrace ();
}
Return visitelement;
}

/**
* Obtain the path name and attribute name and value of the specified child element.
* @ Param document the JDOM document built from listing 2
* @ Param visitednodename: Specifies the name of the child node element to be accessed.
* @ Return returns the specified element.
*/
Public static element getchildelement (Object document, string visitednodename ){
Element visitelement = NULL;
Try {
Visitelement = (element) XPath. selectsinglenode (document, visitednodename );
} Catch (exception e ){
E. printstacktrace ();
}
Return visitelement;
}

/**
* Delete an element in the path of a specified Element Node.
* @ Param removenodename the path of the element to be deleted
* @ Param document the document model corresponding to the XML file
*/
Public static Boolean removechildelement (Object document, string removenodename ){
Element visitelement = NULL;
Boolean isremoved = false;
Try {
Visitelement = (element) XPath. selectsinglenode (document, removenodename );
If (visitelement! = NULL)
Isremoved = visitelement. getparentelement (). removecontent (visitelement );
} Catch (exception e ){
E. printstacktrace ();
}
Return isremoved;
}

/**
* Delete the elements of a specified attribute.
* @ Param document the document model corresponding to the XML file
* @ Param removenodename path of the node element to be deleted
* @ Param attributename attribute name
* @ Param attributevalue Attribute Value
* @ Return
*/
Public static Boolean removechildelement (Object document, string removenodename, string attributename, string attributevalue ){
List removeelements = NULL;
Element visitelement = NULL;
Boolean isremoved = false;
Try {
Removeelements = XPath. selectnodes (document, removenodename + "[@" + attributename + "= '" + attributevalue + "']");
If (removeelements! = NULL ){
For (INT I = 0; I <removeelements. Size (); I ++ ){
Visitelement = (element) removeelements. Get (I );
Isremoved = visitelement. getparentelement (). removecontent (visitelement );
}
}
} Catch (exception e ){
E. printstacktrace ();
}
Return isremoved;
}

/**
* Output the XML document model to the standard output device (screen)
* @ Param document the specified XML document model
*/
Public static void outputdocument (document ){
Format. setindent ("");
Format. setexpandemptyelements (false );
Try {
Xmloutputter outputter = new xmloutputter (format );
Outputter. Output (document, system. Out );
} Catch (exception e ){
E. printstacktrace ();
}
}

/**
* Output the XML document model to the standard output device (Stream)
* @ Param document the specified XML document model
*/
Public static void outputdocument (document, outputstream output ){
Format. setindent ("");
Format. setexpandemptyelements (false );
Try {
Xmloutputter outputter = new xmloutputter (format );
Outputter. Output (document, output );
} Catch (exception e ){
E. printstacktrace ();
}
}

/**
* Output the XML document model to a specified file
* @ Param document the specified XML document model
* @ Param outputfilepath: Path of the output file
*/
Public static void outputdocumenttofile (document, string outputfilepath ){
Outputdocumenttofile (document, outputfilepath, encode_gb2312 );
}

/**
* Output the XML document model to a specified file
* @ Param document the specified XML document model
* @ Param outputfilepath: Path of the output file
* @ Param encodingmode: encoding method
*/
Public static void outputdocumenttofile (document, string outputfilepath, string encodingmode ){
Format. setencoding (encodingmode );
Format. setindent ("");
Format. setexpandemptyelements (false );
Filewriter writer = NULL;

Try {
Xmloutputter outputter = new xmloutputter (format );
Writer = new filewriter (outputfilepath );
Outputter. Output (document, writer );
Writer. Close ();

} Catch (exception EP ){
Ep. printstacktrace ();
}
Finally {
Try {
If (writer! = NULL)
Writer. Close ();
} Catch (ioexception E1 ){
E1.printstacktrace ();
}
}
}

/**
* Output the XML document model to a specified string
* @ Param document the specified XML document model
* @ Return returns the content of the document.
*/
Public static string outputdocumentstring (document ){

Return outputdocumentstring (document, encode_gbk );
}

/**
* Output the XML document model to a specified string
* @ Param document the specified XML document model
* @ Param encodingmode encoding format
* @ Return returns the content of the document.
*/
Public static string outputdocumentstring (document, string encodingmode ){
Format. setencoding (encodingmode );
Format. setindent ("");
Format. setexpandemptyelements (false );
Xmloutputter outputter = new xmloutputter (format );
Return outputter. outputstring (document );
}

/**
* This method takes a JDOM document in memory, an XSL file at XML/car. XSL,
* And outputs the results to stdout.
* This method corresponds to listing 9.
* @ Param mydocument the JDOM document built from listing 2.
*/
// Public static void executexsl (document mydocument ){
// Try {
// Transformerfactory tfactory = transformerfactory. newinstance ();
/// Make the input sources for the XML and XSLT documents
// Org. JDOM. Output. domoutputter outputter = new org. JDOM. Output. domoutputter ();
// Org. W3C. Dom. Document domdocument = outputter. Output (mydocument );
// Javax. xml. Transform. Source xmlsource = new javax. xml. Transform. Dom. domsource (domdocument );
// Streamsource effectsource = new streamsource (New fileinputstream ("car. XSL "));
/// Make the output result for the finished document
///*
// * Note that here we are just going to output the results to
// * System. Out, since we don't actually have a httpresponse object
// * In this example
//*/
/// Streamresult xmlresult = new streamresult (response. getoutputstream ());
// Streamresult xmlresult = new streamresult (system. Out );
/// Get a XSLT transformer
// Transformer = tfactory. newtransformer (transtsource );
/// Do the Transform
// Transformer. Transform (xmlsource, xmlresult );
//} Catch (filenotfoundexception e ){
// E. printstacktrace ();
//} Catch (transformerconfigurationexception e ){
// E. printstacktrace ();
//} Catch (transformerexception e ){
// E. printstacktrace ();
//} Catch (Org. JDOM. jdomexception e ){
// E. printstacktrace ();
//}
//}

/**
* Modifying the attributes of a specified node Element
* @ Param document
* @ Param nodepath
* @ Param name
* @ Param Value
*/
Public static void setelementattributevalue (Object document, string nodepath, string name, string value ){
Try {
(Element) XPath. selectsinglenode (document, nodepath). setattribute (name, value );
} Catch (exception e ){
E. printstacktrace ();
}
}

/**
* Modifying the attributes of a specified node Element
* @ Param document
* @ Param nodepath
* @ Param attrname
* @ Param attrvalue
* @ Param name
* @ Param Value
*/
Public static void setelementattributevalue (Object document, string nodepath, string attrname, string attrvalue, string name, string value ){
Nodepath + = "[@" + attrname + "= '" + attrvalue + "']";
Setelementattributevalue (document, nodepath, name, value );
}
/**
* Modify the content of a specified node Element
* @ Param document
* @ Param nodepath
* @ Param text
*/
Public static void setelementtext (Object document, string nodepath, string text ){
Try {
(Element) XPath. selectsinglenode (document, nodepath). settext (text );
} Catch (exception e ){
E. printstacktrace ();
}
}

/**
* Modify the content of a specified node Element
* @ Param document
* @ Param nodepath
* @ Param attrname
* @ Param attrvalue
* @ Param text
*/
Public static void setelementtext (Object document, string nodepath, string attrname, string attrvalue, string text ){
Nodepath + = "[@" + attrname + "= '" + attrvalue + "']";
Setelementtext (document, nodepath, text );
}

/**
* Set the XML encoding format
* @ Param encode
*/
Public static void setencoding (string encode ){
Format. setencoding (encode );

}

/**
* Use the DTD document type definition to validate the XML document
* @ Param content
* @ Return
*/
// Public static Boolean validate (){
// Saxbuilder builder = new saxbuilder (true );
// Try {
/// JDOM complains about the document even though it is valid
// Bytearrayinputstream BAIS = new bytearrayinputstream (content. getbytes ());
// Builder. Build (BAIS );
// Return true;
//
//} Catch (exception e ){
//
// Return false;
//
//}
//
//}

Public static void main (string [] ARGs) throws exception
{
Document Doc = xmlutil. readdocument ("test. xml ");
List shapes = xmlutil. getchildrenelement (Doc, "javer/LEO/example ");
For (INT I = 0; I {
System. Out. println (xmlutil. getchildelement (shapes. Get (I), "ID"). gettext ());
}
}
}

Faye Wong-Tomu

Lyrics: Yang mingxue
Composing: Yuan weiren
Edited by Huang Zhongyue

With gorgeous appearance and brilliant Lighting
I'm a carousel in this paradise
Only to satisfy the children's dreams
Climb onto my back and take you to soar
I forgot the sorrow that can only run in the same place
I also forgot that I was always locked.
No matter how long I can accompany you
At least make you think about flying with me

The trojan of the Mercedes-Benz makes you forget to hurt
In this paradise that provides laughter
Looking at their envy
Don't worry about me
The rotated trojan has no wings
But it can fly around with you
Music stops and you will leave
That's all I can do.

Feeling like a rotating Trojan, locked by the world, day after day, no dream, can not soar
Maybe, only occasionally flying in the code can I forget that I am always locked

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.