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

标签 java xml xml-parsing jaxb xstream

我有一个非常大且复杂的 xml,我想仅将选定的字段加载到我的对象中。 我尝试过使用 xstream,但我的理解是我的 xml 结构必须与我的 pojo 类似。 我提供示例 i/p 和 o/p 以便更好地理解

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

Pojo 将会

    class Note{
     long noteId;
     String body;

    //getters and setters

   }

问题是如何在将 xml 元素加载到 pojo 时跳过它?

最佳答案

您可以使用Jackson XML librairy来做到这一点。 jackson 可能更出名的是 JSON序列化/反序列化,但它有 XML 扩展。

如果您的 XML 文件很大,请查看上面的链接,了解如何部分/增量读取它以获得最佳性能。

无论如何,以下示例介绍了如何使用 @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
}

带有示例文件:

<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>

还有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()));
    }
}

输出是(注意空字段):

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

您还可以创建一个仅包含您需要的字段的 pojo - 然后不使用 @JsonIgnore 。为此 XmlMapper必须通知忽略未知的 XML 属性。

    XmlMapper mapper = new XmlMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
<小时/>

编辑

您想要一个只有几个字段的 pojo 的情况的完整示例:

假设我们有一个只有 id 的 pojo和title :

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 
}

执行以下命令main()与上面描述的 xml 文件:

公共(public)类 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());
        }
    }
}

将给出:

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

关于java - 如何在加载到 pojo 时跳过 xml 元素(在 xstream/jaxb 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32518319/

相关文章:

java - 按钮未出现在 JFrame 中

java - org.eclipse.core.runtime.Assert 在哪里可用?

java - 如何在 jar 文件的类路径中配置 C3p0.properties 文件以读取类路径外的 C3P0-config.xml

php - 将带有属性的 XML 导入 mysql

Java 替换 xml 中的单词

java - 将 Windows-1252 xml 文件转换为 UTF-8

java - GL11 纹理渲染错误

c# - 在 C# 中从 XML 文档中提取和汇总数据

c# - 没有 Unicode 字节顺序标记。无法切换到 Unicode

c++ - 未定义 schemaLocation 的 libxml2 命名空间前缀