没有根元素的子元素在java中

时间:2014-03-17 20:33:52

标签: java xml jaxb sax stax

我有一个像这样的xml文档:

<root>
    <device>
        <v1>blah</v1>
    </device>
</root>

我想解析这个文档,但只是解析

    <device>
        <v1>blah</v1>
    </device>

一部分。我想忽略根元素。我怎样才能用jaxb解组呢?

2 个答案:

答案 0 :(得分:1)

假设您的JAXB定义对&lt; root&gt;一无所知,即您不能只解组整个事物并查看生成的Root对象:

  1. 解析为文档。
  2. 使用XPath / DOM遍历/无论如何将[a]引用[s]到设备节点[s]。
  3. 使用unmarshaller.unmarshal(节点)。

答案 1 :(得分:0)

您可以执行以下操作:

  • 使用StAX 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();
    }

}

了解更多信息