問題

我想跳過除first_name,node100及其子節點之外的所有節點. 我有這個XML(實際上我有很多員工,每個員工標籤都有很多節點):

  <employees>
        <employee>
            <first_name>John</first_name>
            <last_name>Doe</last_name>
            <age>26</age>
        </employee>
        <employee>
            <first_name>Peter</first_name>
            <last_name>Parker</last_name>
            <age>30</age>
        </employee>
    </employees>
 

我能夠閱讀使用Jackson FasterXML.我建立了2個POJOS來對映上面的XML結構

   @JacksonXmlRootElement(localName = "employees") public final class Employees {
        @JacksonXmlElementWrapper(localName = "employee", useWrapping = false)
        private Employee[] employee;
//ommiteed getter and setters

public final class Employee {
    @JacksonXmlProperty(localName = "id", isAttribute = true)
    private String id;
    @JacksonXmlProperty(localName = "first_name")
    private String firstName;
    @JacksonXmlProperty(localName = "last_name")
    private String lastName;
    @JacksonXmlProperty(localName = "age")
    private int age;
 

現在在生產中,xml在節點內有1000個節點

 <employee>
                <first_name>John</first_name>
                <last_name>Doe</last_name>
                <age>26</age>
                <node1>  </node1>
                <node2>  </node2>

                ..

                <node100> 
                   <values> 
                  <value> val1 </value>
                  <value> val1 </value>
                  <value> val1 </value>
                  <value> val1 </value>
                  </node100> 

            </employee>


    <node100>  is also inside 4-5 nodes (which i have not shown above).
 

所以我的問題是如何讀取first_name,last_name和tag. 我的POJO類的結構應該是什麼?

將XML轉換為POJO的程式碼

 System.out.println( " hello");
ObjectMapper objectMapper = new XmlMapper();
// Reads from XML and converts to POJO
Employees employees = objectMapper.readValue(
        StringUtils.toEncodedString(Files.readAllBytes(Paths.get("C:\Users\91895\Downloads\File\XmlFile.xml")), StandardCharsets.UTF_8),
        Employees.class);
System.out.println(employees);
 

  最佳答案

在您的類中定義您想從XML讀取的元素.相應地忽略其他元素配置ObjectMapper:

 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 

  相同標籤的其他問題

javaxmljacksonjackson-dataformat-xml