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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM