gpt4 book ai didi

Java - 反序列化扁平化的 XML 文件。 (XStream、JAXB、MOXy,以……为准)

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:06 24 4
gpt4 key购买 nike

我目前正在使用 XStream 来解析 XML 文件,但无法让它执行我需要它执行的操作。如果有必要,我会换一个库,只要能解决这个问题!

基本上我正在尝试解析与此类似的 XML 提要:

<product>
<title>Transformers Best of Grimlock</title>
<author1>Bob Budiansky</author1>
<author2>Simon Furman</author2>
</product>

我正在尝试将其解析为这样的模型:

public class Product extends Model {

public String title;

public List<String> authors;

}

标题很漂亮,但我在解析作者时遇到了困难。不幸的是,以这样一种“更合理”的格式获取 XML 提要不是一种选择:

...
<authors>
<author>Bob Budiansky</author>
<author>Simon Furman</author>
</authors>
...

我能做些什么来将“author1”、“author2”等解析成列表吗?

请记住,我是 XStream 的新手(并且根本没有使用过 JAXB!),所以如果我必须编写任何自定义绑定(bind)程序或其他任何东西,我将需要关于从哪里开始的指示。

感谢阅读,我期待任何可以挽救我理智的潜在解决方案! :)


编辑:我更新了帖子以表明我与 XStream 无关。真的很难找到这个问题的答案 - 也许我只是不知道要搜索什么......

最佳答案

以下方法应该适用于任何可以从 StAX XMLStreamReader 解码的 XML 绑定(bind)库。我将在下面使用标准 JAXB (JSR-222) API 进行演示。 (注意:我是 EclipseLink JAXB (MOXy) 领导)。

产品

我们将注释模型,就好像 authors 属性映射到 author 元素一样。

package forum11666565;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Product extends Model {

public String title;

@XmlElement(name = "author")
public List<String> authors;

}

演示

我们将使用 XMLStreamReader 解析 XML 文档。在那个 XMLStreamReader 上,我们将创建一个 StreamReaderDelegate,它将以 author 开头的任何元素报告为名为 author 的元素.

package forum11666565;

import java.io.FileInputStream;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.stream.util.StreamReaderDelegate;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Product.class);

XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream("src/forum11666565/input.xml"));
xsr = new StreamReaderDelegate(xsr) {

@Override
public String getLocalName() {
String localName = super.getLocalName();
if(localName.startsWith("author")) {
return "author";
} else {
return localName;
}
}

};

Unmarshaller unmarshaller = jc.createUnmarshaller();
Product product = (Product) unmarshaller.unmarshal(xsr);

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(product, System.out);
}

}

输入.xml

<product>
<title>Transformers: Best of Grimlock</title>
<author1>Bob Budiansky</author1>
<author2>Simon Furman</author2>
</product>

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<product>
<title>Transformers: Best of Grimlock</title>
<author>Bob Budiansky</author>
<author>Simon Furman</author>
</product>

关于Java - 反序列化扁平化的 XML 文件。 (XStream、JAXB、MOXy,以……为准),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11666565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com