Tips for conversion between irregular xml and JAVA objects-use javasaller

Source: Internet
Author: User

Tips for conversion between irregular xml and JAVA objects-use javasaller
Abstract: It is common to convert XML documents and JAVA objects. If the XML definition is regular, this is a good implementation. However, in reality, XML with "no rules" may be more common. Is it powerless to use Marshaller? The following is a little trick. You can adjust your mind to reuse Marshaller and conquer them to make your work easier. Keywords: Marshaller, JAVA, XML generate a Json string for a class, translate a Json string into a class (JAVA, C # code ), this process has been described in the "" blog; in actual project applications, how to generate an XML document or XML string for a class, and how to translate an XML document into a class, this is a common problem. For example, in interaction with other systems, interface parameters defined by other systems are defined in XML format, then the system you write must parse and understand the data it imports, or convert your internal data to a document in the XML format specified by the document. In JAVA, this process is quite simple, and it can be easily solved by using Marshaller. However, some "unruly" XML formats may be defined by other systems. The XML formats defined by them are not exactly the inherent ability of Marshaller to generate and parse, are we not able to implement this "unruly" XML? In fact, Marshaller is still very useful, and you will find that the limit of Marshaller no longer exists. Below, I will use a simple example to prove my point of view. For "unruly" XML, I also have a way to uniform it. 1. XML help class first, you must have an XML help class that provides the most basic information. It uses Marshaller to convert XML and JAVA objects. This is for regular XML documents, it can be a block of hundreds. Import javax. xml. bind. JAXBContext; import javax. xml. bind. JAXBException; import javax. xml. bind. marshaller; import javax. xml. bind. unmarshaller; /*** XML help class ** @ author wanganqi * @ version v1.0 * @ since August 13, 2014 2:38:52 */public class XmlHelper {/*** convert the custom data object XML String ** @ param clazz custom data type * @ param object Custom Data object * @ return XML String * @ throws JAXBException */public static String objectToXML (CIA Ss clazz, Object object) throws JAXBException {String xml = null; JAXBContext context = JAXBContext. newInstance (clazz); extends aller m = context. createMarshaller (); m. setProperty (exploraller. JAXB_FORMATTED_OUTPUT, Boolean. TRUE); Writer w = new StringWriter (); m. marshal (object, w); xml = w. toString (); return xml ;} /*** convert an XML string to a custom data object ** @ param clazz custom data type * @ param xml string * @ return Custom Data Object * @ Throws JAXBException */public static Object xmlToObject (Class clazz, String xml) throws JAXBException {JAXBContext context = JAXBContext. newInstance (clazz); Unmarshaller um = context. createUnmarshaller (); return um. unmarshal (new StringReader (xml) ;}} for such a rule: XML, we need to define such a: JAVA class, one-to-one correspondence, and everything can be solved. JAVA Generation Method for XML (regular) File Format examples <? Xml version = "1.0" encoding = "UTF-8"?> <ANQIFILE> <HEAD> <ANQINUM> 2 </ANQINUM> <DATETIME> YYYY-MM-DD HH: MM: SS </DATETIME> <APPROVALNUM> Wang ANQI No1 </APPROVALNUM> </HEAD> <BODY> <ANQI> 00001 </ANQI> <ANQI> 00002 </ANQI> <ANQI> 00003 </ANQI> </BODY> </ANQIFILE> ANQIHead head = new ANQIHead (1, "YYYY-MM-DD HH: MM: SS", "Wang Anqi No1"); ANQIBody body = new ANQIBody ("00001", "00002", "00003 "); ANQIFile anqiFile = new ANQIFile (head, body); String xml = XmlHelper. objectid XML (ANQIFile. class, anqiFile. @ XmlRootElement (name = "ANQIFILE") @ XmlType (propOrder = {"head", "body"}) public class ANQIFile {private ANQIHead head; private ANQIBody body; @ XmlElement (name = "HEAD") public ANQIHead getHead () {return head;} public void setHead (ANQIHead head HEAD) {this. head = head ;}@ XmlElement (name = "BODY") public ANQIBody getBody () {return body;} public void setBody (ANQIBody body BODY) {this. body = body ;}}---- Extends public class ANQIBody {private List <String> anqi; @ XmlElement (name = "ANQI") public List <String> getAnqi () {return anqi ;} public void setAnqi (List <String> anqi) {this. anqi = anqi ;}@ XmlType (propOrder = {"anqiNum", "dateTime", "appovalNum"}) public class ANQIHead {private int anqiNum; private String dateTime; pri Vate String appovalNum; @ XmlElement (name = "ANQINUM") public int getAnqiNum () {return clueNum;} public void setAnqiNum (int clueNum) {this. clueNum = clueNum;} @ XmlElement (name = "DATETIME") public String getDateTime () {return dateTime;} public void setDateTime (String dateTime) {this. dateTime = dateTime;} @ XmlElement (name = "APPROVALNUM") public String getAppovalNum () {return appovalNum ;} Public void setAppovalNum (String appovalNum) {this. appovalNum = appovalNum;} note: the constructor here is hidden. Use String... the anqis parameter is similar. Do not be confused when using it. 2. Convert custom data objects to XML (irregular) strings. Now we have a requirement to convert the JAVA objects of our system into XML Format documents specified by other systems, other systems provide us with an XML document, hoping that we can construct it correctly. The system I wrote needs to parse and understand the XML data imported by other systems, other systems provide us with an XML document. We hope we can explain it smoothly. Let's see how we did it. XML format: XML (irregular) File Format example JAVA usage and JAVA class <? Xml version = "1.0" encoding = "UTF-8"?> <ANGELFILE> <ANGEL> <wang id = "00001" COUNT = "2"> <ANQI> <ITEM1> VALUE </ITEM1> <ITEM2> VALUE </ITEM2> <ITEMN> VALUE </ITEMN> </ANQI> <ITEM1> VALUE </ITEM1> <ITEM2> VALUE </ITEM2> <ITEMN> VALUE </ITEMN> </ANQI> </WANG> </ANGEL> </ANGELFILE> you can use JAVA definitions and usage methods similar to the preceding XML rules. Now let's take a look at how undisciplined it is (in fact, it is not very irregular, but the sub-node names under the ANQI node are different, but they all start with items ). To generate such XML, You can first use ObjectToXML () to generate a node named after ITEM, then read and update the ITEM name through DOM, followed by 1, 2... to parse such XML, You can first filter the XML, update the node name of the ITEM * sample to ITEM, and then generate an object using XMLToObject. Iii. Problems encountered and improvement methods 1. A problem occurred while using exploraller: when generating XML, the @ XmlType (propOrder = {"1 ", "2"}), but the opposite is true. This problem has not been solved yet. The only information found on the internet is that the BUG may occur if the JAVA version is below 6, however, this problem also occurs when my JAVA version is 1.7. If you know the solution, please kindly advise. 2. For irregular XML format, the better way is to use the custom parser supported by Marshaller. The above irregular XML can be fully mapped to the Map object. This method supports more irregular XML definitions. I do not know whether the code has been implemented on the Internet. If you know the code, please do not give me any further advice. Recently, the project has a huge workload and I learned a lot every day. Project Management, JAVA usage, and interface specifications ...... after all, it is the first time that you are in charge of a project. There are huge experiences and lessons to be learned. As a project manager, I feel that I have a deep sense of responsibility and pressure on my work and my team. Thanks to the trust and support of the Organization, thanks to the cooperation of the team, the cooperation of relevant departments, the selfless help of teacher Yao, and the support of his wife.

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.