我有一个像这样的xml文档:
<root>
<device>
<v1>blah</v1>
</device>
</root>
我想解析这个文档,但只是解析
<device>
<v1>blah</v1>
</device>
一部分。我想忽略根元素。我怎样才能用jaxb解组呢?
答案 0 :(得分:1)
假设您的JAXB定义对&lt; root&gt;一无所知,即您不能只解组整个事物并查看生成的Root对象:
答案 1 :(得分:0)
您可以执行以下操作:
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();
}
}
了解更多信息