JAXBContext中bean和xml之间的转换,以及xml相关的方法
@Data @AllArgsConstructor @NoArgsConstructor //需要无惨构造器 @XmlRootElement public class ClassA { private String file1; private String file2; }
测试类
public class jbTest { public static void main(String[] args) { // bean转换成xml ClassA a=new ClassA("hello string","hello int"); System.out.println(a); try { JAXBContext context = JAXBContext.newInstance(ClassA.class); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(a,System.out); } catch (JAXBException e) { e.printStackTrace(); } printLine(); // xml转换成bean String xmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<classA><file1>hello string</file1><file2>hello int</file2></classA>"; try { JAXBContext context = JAXBContext.newInstance(ClassA.class); Unmarshaller unmarshaller = context.createUnmarshaller(); ClassA a2 = (ClassA) unmarshaller.unmarshal(new StringReader(xmlStr)); System.out.println(a2); } catch (JAXBException e) { e.printStackTrace(); } } public static void printLine(){ System.out.println("==============================="); } }
XStream使用(序列号xml)
导入pom文件
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream --> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.11.1</version> </dependency>
测试代码
XStream stream=new XStream(); stream.alias("hellowolrd",String.class); String str = stream.toXML("str"); System.out.println(str); // 结果: // <hellowolrd>str</hellowolrd>
这是基本用法,然后可以根据自己的需求扩展
Document使用拼接xml格式的文件
导入pom文件
<!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
测试代码和结果:
Document root= DocumentHelper.createDocument(); Element html = root.addElement("html"); html.addElement("body").addText("txt_body"); html.addElement("head").addText("txt_head"); System.out.println(root.asXML()); // 结果 // <?xml version="1.0" encoding="UTF-8"?> // <html><body>txt_body</body><head>txt_head</head></html>