【发布时间】:2014-03-17 20:33:51
【问题描述】:
我有一个这样的 xml 文档:
<root>
<device>
<v1>blah</v1>
</device>
</root>
我想解析这个文档,但只是
<device>
<v1>blah</v1>
</device>
部分。我想忽略根元素。如何使用 jaxb 解组?
【问题讨论】:
我有一个这样的 xml 文档:
<root>
<device>
<v1>blah</v1>
</device>
</root>
我想解析这个文档,但只是
<device>
<v1>blah</v1>
</device>
部分。我想忽略根元素。如何使用 jaxb 解组?
【问题讨论】:
假设您的 JAXB 定义对
【讨论】:
您可以执行以下操作:
XMLStreamReader 解析 XML。XMLStreamReader 推进到您要解组的元素。XMLStreamReader 的解组方法之一。示例
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class UnmarshalDemo {
public static void main(String[] args) throws Exception {
// Parse the XML with a StAX XMLStreamReader
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
// Advance the XMLStreamReader to the element you wish to unmarshal
xsr.nextTag();
while(!xsr.getLocalName().equals("device")) {
xsr.nextTag();
}
// Use one of the unmarshal methods that take an XMLStreamReader
JAXBContext jc = JAXBContext.newInstance(Device.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Device device = (Device) unmarshaller.unmarshal(xsr);
xsr.close();
}
}
更多信息
【讨论】: