使用Jackson将包含模式和数据的Xml转换为Java对象

时间:2018-08-24 04:11:30

标签: java xml jackson

我已经尝试了Jackson API将XML下面的XML解析为java对象,但是没有用。我只想要代表学生记录的对象。有人可以帮我吗?对于标准xml格式,Jackson API可以使用,但对于以下示例,我无法做到这一点

pipeline {
    agent any
    stages {
        stage('No-op') {
            steps {
                sh 'ls'
            }
        }
    }
    post {
        always {
            echo 'One way or another, I have finished'
            deleteDir() /* clean up our workspace */
        }
        success {
            echo 'I succeeeded!'
        }
        unstable {
            echo 'I am unstable :/'
        }
        failure {
            echo 'I failed :('
        }
        changed {
            echo 'Things were different before...'
        }
    }
}

1 个答案:

答案 0 :(得分:2)

SimpleXml可以做到,第一个POJO:

public class StudentRecord {
    @XmlAttribute
    @XmlName("diffgr:id")
    public String id;
    @XmlAttribute
    @XmlName("msdata:rowOrder")
    public int rowOrder;
    @XmlName("StudentId")
    public String studentId;
    @XmlName("FName")
    public String firstName;
    @XmlName("LName")
    public String lastName;
    @XmlName("Address1")
    public String address1;
}

接下来,我们将XML转换为DOM,然后获取所需的元素并将其转换为类。

final SimpleXml simple = new SimpleXml();
final Element root = simple.fromXml(xml);
final StudentRecord student = simple.fromXml(root.children.get(1).children.get(0).children.get(0), StudentRecord.class);
System.out.println(student.id + " : " + student.firstName + " " + student.lastName);

此代码将打印:

StudentRecord1 : ABC DSF

SimpleXml位于Maven中央:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.5.5</version>
</dependency>