XML Tool class that provides methods for serializing XML, deserializing XML, and getting the value of a specified node.
The source code is as follows: (Click to download- xmlutils.java,dom4j-1.6.1.jar,xstream-1.4.7.jar )
1 Importorg.dom4j.Document;2 Importorg.dom4j.DocumentException;3 ImportOrg.dom4j.DocumentHelper;4 Importorg.dom4j.Element;5 ImportCom.thoughtworks.xstream.XStream;6 7 /**8 * XML Tool Class9 * Ten */ One Public classXmlutils { A - Private Final StaticString xml_declaration = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>"; - the Privatexmlutils () { - } - - /** + * Serialization of XML - * + * @paramobj A * @paramClazz at * @return - */ - Public Static<T>String ToXML (Object obj) { -XStream stream =Getxstream (); - stream.processannotations (Obj.getclass ()); - return NewStringBuffer (xml_declaration). Append (Stream.toxml (obj)). toString (); in } - to /** + * Deserialization of XML - * the * @paramXmlstr * * @paramClazz $ * @returnPanax Notoginseng */ - Public Static<T> T FromXml (String xmlstr, class<t>clazz) { theXStream stream =Getxstream (); + stream.processannotations (clazz); AObject obj =Stream.fromxml (XMLSTR); the Try { + returnclazz.cast (obj); -}Catch(classcastexception e) { $ return NULL; $ } - } - the /** - * Gets the value of the specified nodeWuyi * the * @paramXPath - * @paramparams Wu * @return - */ About Public Staticstring Getnodevalue (String xpath, string datastr) { $ Try { - //to convert a string to XML -Document document =Documenthelper.parsetext (DATASTR); - //Find Nodes AElement element =(Element) Document.selectsinglenode (XPath); + if(Element! =NULL) { the returnElement.getstringvalue (); - } $}Catch(documentexception e) { the e.printstacktrace (); the } the return""; the } - in /** the * Get XStream instances the * About * @return the */ the Public StaticXStream Getxstream () { the return NewXStream (); + } -}
XML Tool Class-Xmlutils.java