未尝不可以这样做

  

 

public static void main(String[] args) {
		// TODO Auto-generated method stub
		doXML_Method_a();
		System.out.println();
		doXML_Method_b();
	}

	public static void doXML_Method_a() {
		String tmp = "<UserBean><id><![CDATA[%s]]></id><userName><![CDATA[%s]]></userName><passwd><![CDATA[%s]]></passwd><token>%s</token></UserBean>";
		System.out.println(String.format(tmp, "Admin", "Guest", "root",
				"hello xml"));
	}

	public static void doXML_Method_b() {
		XStream xstream = new XStream();
		xstream.alias("UserBean", UserBean.class);
		UserBean user = new UserBean();
		user.setId(UUID.randomUUID().toString());
		user.setUserName("Guest");
		user.setPasswd(UUID.randomUUID().toString());
		user.setToken("hello xml");
		System.out.println(xstream.toXML(user));
	}

 

 

<UserBean><id><![CDATA[Admin]]></id><userName><![CDATA[Guest]]></userName><passwd><![CDATA[root]]></passwd><token>hello xml</token></UserBean>

<UserBean>
  <id>febd3ccb-6a15-44c4-9fd5-27b05d60728a</id>
  <userName>Guest</userName>
  <passwd>ccaea943-049f-4dc8-be0d-46b9c687b895</passwd>
  <token>hello xml</token>
</UserBean>

 

 

public class XStreamFactory {
	protected static String PREFIX_CDATA = "<![CDATA[";
	protected static String SUFFIX_CDATA = "]]>";

	/**
	 * 初始化XStream 可支持某一字段可以加入CDATA标签 如果需要某一字段使用原文
	 * 就需要在String类型的text的头加上"<![CDATA["和结尾处加上"]]>"标签, 以供XStream输出时进行识别
	 * 
	 * @param isAddCDATA
	 *            是否支持CDATA标签
	 * @return
	 */
	public static XStream init(boolean isAddCDATA) {
		XStream xstream = null;
		if (isAddCDATA) {
			xstream = new XStream(new XppDriver() {
				public HierarchicalStreamWriter createWriter(Writer out) {
					return new PrettyPrintWriter(out) {
						protected void writeText(QuickWriter writer, String text) {
							if (!text.startsWith(PREFIX_CDATA)) {
								text = PREFIX_CDATA + text + SUFFIX_CDATA;
							}
							writer.write(text);
						}
					};
				};
			});
		} else {
			xstream = new XStream();
		}
		return xstream;
	}
}

 

你可能感兴趣的:(未尝不可以这样做)