gpt4 book ai didi

java - 使用 JAXB 解码将 XML 转换为 Java

转载 作者:行者123 更新时间:2023-11-30 04:04:52 26 4
gpt4 key购买 nike

我使用下面的代码将 XML 解码为一组 Java 类(从 xsd 生成的类)。

JAXBContext jc = JAXBContext.newInstance(BlockType.class);
StreamSource xml = new StreamSource("C:\\Users\\Se\\Desktop\\watch2.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<BlockType> je1 = unmarshaller.unmarshal(xml, BlockType.class);

BlockType cgwt = je1.getValue();

必须解码的 XML 在其开头有这样一行:

<test:MessageBlock xsi:schemaLocation="http://www.test.com/Watch/v2.1 Test_WatchSchema_v2.1.xsd">

如果我删除 test: 和 xsi:.... XML 就会正确解码。然而,如果我让他们我得到

[org.xml.sax.SAXParseException: The prefix "test" for element "test:CargoWatchMessageBlock" is not bound.]

我该如何解决这个问题?

最佳答案

如果使用了 test 前缀,则 XML 文档中应该有一个 xmlns:test 属性。如果没有该属性声明前缀,您应该从文档中删除该前缀才能使其有效。

<小时/>

更新

I do not control the document so I guess I'll have to find some workaround for removing the test: prefix and xsi: before unmarshalling.

下面是一个示例的链接,它应该可以帮助您构建您正在寻找的内容。它利用 JAXB 的 UnmarshallerHandler 和 SAX 解析器将前缀视为元素名称的父元素。

关于java - 使用 JAXB 解码将 XML 转换为 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20997421/

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