简体   繁体   English

如何在加载到pojo中时跳过xml元素(在xstream / jaxb中)

[英]how to skip xml elements while loading into pojo (in xstream/jaxb)

I have a very big and complex xml and i want to load only selected fields into my object. 我有一个非常大和复杂的xml,我只想将选定的字段加载到我的对象中。 I have tried with xstream but what i understood is my xml structure must be similar to my pojo. 我已经尝试过使用xstream,但是我了解的是我的xml结构必须类似于我的pojo。 I am providing sample i/p and o/p for better understanding 我提供样本i / p和o / p以便于更好地理解

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Pojo will be 波乔将

    class Note{
     long noteId;
     String body;

    //getters and setters

   }

Question is how to skip xml elements while loading it into pojo? 问题是在将XML加载到pojo中时如何跳过xml元素?

You can do it with Jackson XML librairy . 您可以使用Jackson XML librairy做到这一点 Jackson is maybe more famous for JSON serialising/deserialising but it has a XML extension. Jackson可能以JSON序列化/反序列化而闻名,但它具有XML扩展名。

If your XML file is big, look at the above link to see how you can partially/incrementally read it in order to get the best performances. 如果您的XML文件很大,请查看上面的链接,以了解如何部分/递增地读取它以获得最佳性能。

Anyway following is an example on how to read only a subset of properties using the @JsonIgnore annotation on the fields you don't want deserialised: 无论如何,以下是一个示例,该示例说明如何在不需要反序列化的字段上使用@JsonIgnore批注仅读取属性的子集

@JacksonXmlRootElement(localName = "jokes")
class Jokes {

    @JacksonXmlProperty(localName = "joke")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Joke[] jokes;

    // getter, setter omitted
}

class Joke {
    @JacksonXmlProperty(isAttribute = true)
    long id;

    @JacksonXmlProperty(localName = "title")
    String title;

    @JsonIgnore
    String author;

    @JacksonXmlProperty(localName = "like")
    long like;

    @JsonIgnore
    String content;

    public String toString() {
        return Arrays.stream(new Object[] {id, title, author, like, content})
                .map(o -> o!=null ? o.toString() : "EMPTY")
                .collect(Collectors.joining(", ", "[", "]"));
    }

    // getters, setters omitted
}

With a sample file: 带有示例文件:

<jokes>
    <joke id="123">
        <title>C'est l'histoire d'un mec</title>
        <author>Coluche</author>
        <content>Blah blah blah</content>
        <like>4509</like>
    </joke>
    <joke id="777">
        <title>Si j'ai bien tout lu freud</title>
        <author>Coluche</author>
        <content>Blah blah blah</content>
        <like>345</like>
    </joke>
</jokes>

And the main() main()

public class XmlJokeReader {

    public static void main(String[] args) throws JsonProcessingException, IOException {
        XmlMapper mapper = new XmlMapper();

        Jokes jokesDoc = mapper.readValue(new File("./data/jokes.xml"), Jokes.class);
        Arrays.stream(jokesDoc.getJokes()).forEach(j -> System.out.println(j.toString()));
    }
}

The output is (note the EMPTY fields): 输出为(请注意EMPTY字段):

[123, C'est l'histoire d'un mec, EMPTY, 4509, EMPTY] [123,C'est l'histoire d'un mec,EMPTY,4509,EMPTY]
[777, Si j'ai bien tout lu freud, EMPTY, 345, EMPTY] [777,空姐,空姐,345,空姐]

You can also create a pojo that contains only the fields you need - then not using @JsonIgnore . 您还可以创建仅包含所需字段的@JsonIgnore然后不使用@JsonIgnore For that the XmlMapper has to be informed to ignore unknown XML properties. 为此,必须通知XmlMapper忽略未知的XML属性。

    XmlMapper mapper = new XmlMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

EDIT 编辑

The full example for the case where you want a pojo with only a few fields: 您只需要几个字段的pojo的完整示例:

Let say we have a pojo with only id and title : 假设我们有一个只有idtitle的pojo:

class Joke {
    @JacksonXmlProperty(isAttribute = true)
    long id;

    @JacksonXmlProperty(localName = "title")
    String title;

    public String toString() {
        return new StringBuffer().append('[')
                .append(id).append(',')
                .append(title).append(']').toString();
    }
    // getters setters 
}

Executing the following main() with the xml file described above: 使用上述xml文件执行以下main()

public class XmlJokeReader { 公共类XmlJokeReader {

    public static void main(String[] args) throws JsonProcessingException, IOException {
        XmlMapper mapper = new XmlMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        Jokes jokesDoc = mapper.readValue(new File("./data/jokes.xml"), Jokes.class);
        for (Joke joke : jokesDoc.getJokes()) {
           System.out.println(joke.toString());
        }
    }
}

Will give: 会给:

[123,C'est l'histoire d'un mec] [123,C'est l'histoire d'un mec]
[777,Si j'ai bien tout lu freud] [777,Si j'ai bien tout lu freud]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM