【问题标题】:Child element without root element in javajava中没有根元素的子元素
【发布时间】:2014-03-17 20:33:51
【问题描述】:

我有一个这样的 xml 文档:

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

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

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

部分。我想忽略根元素。如何使用 jaxb 解组?

【问题讨论】:

    标签: java xml jaxb sax stax


    【解决方案1】:

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

    1. 解析成文档。
    2. 使用 XPath / DOM 遍历 / 任何方法来获取设备节点 [s] 的 [a] 引用。
    3. 使用 unmarshaller.unmarshal(节点)。

    【讨论】:

    • 如果您使用 StAX 解析器而不是 DOM,您将获得更好的性能:stackoverflow.com/a/22464911/383861
    • 确实如此,但是“Advance...to the element you want to unmarshal”可能很重要,特别是如果您想解析该元素的属性或者您无法按元素检测姓名。显然,如果文档很大或者在相关元素之后有大量内容,那么您想要流式传输,但我(个人)只有在从内存或性能角度分析成文档时才会流式传输。
    【解决方案2】:

    您可以执行以下操作:

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

    更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 2014-08-14
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多