public Document serialize(Object object, Document doc) { Class c = object.getClass(); Integer id = getID(object); map.put(object, id); String mapSize = Integer.toString(map.size()); // creating serialization objects Element objectElement = new Element("object"); objectElement.setAttribute(new Attribute("class", c.getName())); objectElement.setAttribute(new Attribute("id", mapSize)); doc.getRootElement().addContent(objectElement); if (!c.isArray()) // class is not an array { Field[] fields = c.getDeclaredFields(); ArrayList<Element> fieldXML = serializeFields(fields, object, doc); for (int i = 0; i < fieldXML.size(); i++) { objectElement.addContent(fieldXML.get(i)); } } else // class is an array { Object array = object; objectElement.setAttribute(new Attribute("length", Integer.toString(Array.getLength(array)))); if (c.getComponentType().isPrimitive()) // class is array of primitives { for (int i = 0; i < Array.getLength(array); i++) { Element value = new Element("value"); value.setText(Array.get(c, i).toString()); objectElement.addContent(value); } } else // class is array of references { for (int j = 0; j < Array.getLength(array); j++) { Element ref = new Element("reference"); id = getID(Array.get(c, j)); if (id != -1) { ref.setText(Integer.toString(id)); } } for (int k = 0; k < Array.getLength(array); k++) { serialize(Array.get(array, k), doc); } } } if (currentElement == 0) { referenceID = 0; } return doc; }
/** * Creates a SAX XMLReader. * * @return <code>XMLReader</code> a SAX2 parser. * @throws Exception if no parser can be created. */ protected XMLReader createParser() throws Exception { XMLReader parser = null; // Try using JAXP... // Note we need JAXP 1.1, and if JAXP 1.0 is all that's // available then the getXMLReader call fails and we skip // to the hard coded default parser try { Class<?> factoryClass = Class.forName("javax.xml.parsers.SAXParserFactory"); // factory = SAXParserFactory.newInstance(); Method newParserInstance = factoryClass.getMethod("newInstance"); Object factory = newParserInstance.invoke(null); // jaxpParser = factory.newSAXParser(); Method newSAXParser = factoryClass.getMethod("newSAXParser"); Object jaxpParser = newSAXParser.invoke(factory); // parser = jaxpParser.getXMLReader(); Class<? extends Object> parserClass = jaxpParser.getClass(); Method getXMLReader = parserClass.getMethod("getXMLReader"); parser = (XMLReader) getXMLReader.invoke(jaxpParser); } catch (ClassNotFoundException e) { // e.printStackTrace(); } catch (InvocationTargetException e) { // e.printStackTrace(); } catch (NoSuchMethodException e) { // e.printStackTrace(); } catch (IllegalAccessException e) { // e.printStackTrace(); } // Check to see if we got a parser yet, if not, try to use a // hard coded default if (parser == null) { parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); } return parser; }