1. 把java中的字段转译成xml格式显示出来并注入相应的值
Bookbook=newBook();
book.setName("zhangsan");
JAXBContextcontext=JAXBContext.newInstance(Book.class);余稿
行纯Marshallermarshaller=context.createMarshaller();档毁咐
marshaller.marshal(book,System.out);
//Book类头上要加@xmlRootElemet
2. java 把“<"输出到xml文件---xml转义问题
xml转义字符替换:
public void escape_xml_with_straight_java () {
static final String ESCAPED_XML =
"<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"
StringBuilder escapedXML = new StringBuilder();
for (int i = 0; i < XML_TO_ESCAPE.length(); i++) {
char c = XML_TO_ESCAPE.charAt(i);
switch (c) {
case '<':
escapedXML.append("<");
break;
case '>':
escapedXML.append(">");
break;
case '\"':
escapedXML.append(""");
break;
case '&':
escapedXML.append("&");
break;
case '\'':
escapedXML.append("'");
break;
default:
if (c > 0x7e) {
escapedXML.append("" + ((int) c) + ";");
} else
escapedXML.append(c);
}
}
assertEquals(ESCAPED_XML, escapedXML.toString());
}
总体思路就是遇到特殊字符,如"<",用"<"来替换就可以了。
3. java如何还原xml中的转义字符
忽略转义的工具类, org.apache.commons.lang.StringEscapeUtils,其中unescapeJava(String s)方法是来处理java转义字符的,可以将字符串中的 “\”转换为 “\”,“'”转换为“'”等。通过这个方法处理以上字符串
public class Test(){ public static void main(String[] args) { String s = "\\u79fb\\u52a8\\u4e92\\u8054\\u7f51\\u5e94\\u7528"; String s2 = StringEscapeUtils.unescapeJava(s); System.out.println(s); System.out.println(s2); } }
输出结果: \u79fb\u52a8\u4e92\u8054\u7f51\u5e94\u7528移动互联网应用