对象转xml并保存到文件

@param object
@return
970903
public static boolean toXml(Object object, File xml) {
        if (object == null) {
            throw new NullPointerException("object对象不存在!");
        }
        JAXBContext jc = null;
        Marshaller m = null;
        try {
            jc = JAXBContext.newInstance(object.getClass());
            m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            m.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
            m.marshal(object, xml);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
110580
public static String format(Object object) {
        Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(gson.toJson(object));
        String prettyJsonString = gson.toJson(je);
        //简单处理function
        String[] lines = prettyJsonString.split("\n");
        lines = replaceFunctionQuote(lines);
        StringBuilder stringBuilder = new StringBuilder();
        for (String line : lines) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
591125
public ItemDocument copy(ItemDocument object) {
		return dataObjectFactory.getItemDocument(
				copy(object.getEntityId()),
				copyMonoLingualTextValues(object.getLabels().values()),
				copyMonoLingualTextValues(object.getDescriptions().values()),
				copyAliasMap(object.getAliases()),
				copyStatementGroups(object.getStatementGroups()),
				copySiteLinks(object.getSiteLinks()),
				object.getRevisionId());
	}
18526
public static void objectToXML(Object object, String fileName) throws FileNotFoundException {
		FileOutputStream fo = new FileOutputStream(fileName);
		XMLEncoder encoder = new XMLEncoder(fo);
		encoder.writeObject(object);
		encoder.close();
	}
635792
public static String toXML(Object object, String encoding, boolean nodeMode) throws MarshalException {

		Properties properties = new Properties();
		properties.put("node", Boolean.toString(nodeMode));
		properties.put("lowcase", "true");
		properties.put("pretty", "true");
		properties.put("cdata", "true");
		properties.put("indent", "\t");
		properties.put("endofline", "\n");
		properties.put("document-start", String.format("<?xml version='1.0' encoding='%s'?>", encoding));
			
		String xml = toXML(object, encoding, properties);
		return xml;
		
	}
577558
@SuppressWarnings("unchecked")
    private void cachingXmlZealots() {
        Map<String, String> xmlMaps = XmlContext.INSTANCE.getXmlPathMap();

        // 遍历所有的xml文档，将每个zealot节点缓存到ConcurrentHashMap内存缓存中
        for (Map.Entry<String, String> entry: xmlMaps.entrySet()) {
            String nameSpace = entry.getKey();
            String filePath = entry.getValue();

            // 根据文件路径获取对应的dom4j Document对象.
            Document doc = XmlNodeHelper.getDocument(filePath);
            if (doc == null) {
                throw new ConfigNotFoundException("注意：未找到配置文件中xml对应的dom4j Document文档,nameSpace为:" + nameSpace);
            }

            // 获取该文档下所有的zealot元素,
            List<Node> zealotNodes = doc.selectNodes(ZealotConst.ZEALOT_TAG);
            for (Node zealotNode: zealotNodes) {
                String zealotId = XmlNodeHelper.getNodeText(zealotNode.selectSingleNode(ZealotConst.ATTR_ID));
                if (StringHelper.isBlank(zealotId)) {
                    throw new NodeNotFoundException("该xml文件中有zealot节点的zealotId属性为空，请检查！文件为:" + filePath);
                }

                // zealot节点缓存到Map中，key是由nameSpace和zealot id组成,用"@@"符号分隔,value是zealotNode
                String zealotKey = StringHelper.concat(nameSpace, ZealotConst.SP_AT, zealotId);
                AbstractZealotConfig.getZealots().put(zealotKey, zealotNode);
            }
        }
    }
798364
public static final String defaultToString(Object object)
   {
      if (object == null)
         return "null";
      else
         return object.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(object));
   }
329913
public T slash(@Nullable Object object) {

		object = object instanceof Optional ? ((Optional<?>) object).orElse(null) : object;

		if (object == null) {
			return getThis();
		}

		String path = object.toString();

		if (path.endsWith("#")) {
			path = path.substring(0, path.length() - 1);
		}

		if (!StringUtils.hasText(path)) {
			return getThis();
		}

		path = path.startsWith("/") ? path : "/".concat(path);

		return slash(UriComponentsBuilder.fromUriString(path).build(), false);
	}
818781
public static <T> String toXml(Class<T> clazz, T object) {
    return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object);
  }
618649
public ObjectMetadata getMetadata(final ValidationObject object)
    {
        if (m_enabled)
        {
            m_validationEngine.clean(object);
        }
        return object.getMetadata();
    }
1144861
public String serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(object);
			return new String(Base64.encodeBase64(bos.toByteArray()));
		} catch (IOException e) {
			LOGGER.error("Can't serialize data on Base 64", e);
			throw new IllegalArgumentException(e);
		} catch (Exception e) {
			LOGGER.error("Can't serialize data on Base 64", e);
			throw new IllegalArgumentException(e);
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
			} catch (Exception e) {
				LOGGER.error("Can't close ObjetInputStream used for serialize data on Base 64", e);
			}
		}
	}
120866
public static void saveXML(Document document, File file) {
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = null;
		try {

			xmlWriter = new XMLWriter(new FileOutputStream(file), format);
			xmlWriter.write(document);

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (xmlWriter != null) {
				try {
					xmlWriter.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
824969
public String serialize(Object object) throws ConverterException {
	deep = 0;

	StringBuilder sb = new StringBuilder();
	if (xmlConform) sb.append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>");
	sb.append("<wddxPacket version=" + del + "1.0" + del + ">");
	deep++;
	sb.append(goIn() + "<header/>");
	sb.append(goIn() + "<data>");
	sb.append(_serialize(object, new HashSet<Object>()));
	sb.append(goIn() + "</data>");
	deep--;
	sb.append("</wddxPacket>");
	return sb.toString();
    }
264505
public <T> String marshal(final T object) {

        if (object == null) {
            throw new IllegalArgumentException("object parameter is null");
        }

        ObjectWriter writer = objectMapper.writer().withDefaultPrettyPrinter();
        String results = null;
        try {
            results = writer.writeValueAsString(object);
        } catch (JsonGenerationException e) {
            System.err.println("JsonGenerationException, message=" + e.getMessage());
        } catch (JsonMappingException e) {
            e.printStackTrace();
            System.err.println("JsonMappingException, message=" + e.getMessage());
        } catch (IOException e) {
            System.err.println("IOException, message=" + e.getMessage());
        }

        return (results);
    }
884574
public static String serialize(Object object) {
	if (object == null) return "[null]";
	try {
	    return new ScriptConverter().serialize(object);
	}
	catch (Throwable t) {
	    ExceptionUtil.rethrowIfNecessary(t);
	    return object.toString();
	}
    }
676946
public static void serializeObjectToFile(Object object, String filename) {
    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
      fos = new FileOutputStream(filename);
      out = new ObjectOutputStream(fos);
      out.writeObject(object);
      out.close();
    } catch(IOException ex) {
      ex.printStackTrace();
      System.exit(1);
    }    
  }
1121145
public static <T extends Saveable> void save(@Nonnull T object) throws IOException {
        if (!BulkChange.contains(object)) {
            XmlFile file = getConfigFile(object.getClass());
            file.write(object);
            SaveableListener.fireOnChange(object, file);
        }
    }