如何提高Jaxb unmarshaller的性能

时间:2014-06-20 07:29:04

标签: java xml jaxb

我想像下面那样编组和解组:
 我想从<keyName>value</keyName>解组xml到HashMap

class A{
     private String name;

     private List<B> list;
    }

    class B{
     private Map <String, String> map;
    }

XML:

<A>
  <name>name</name>
  <BList>
    <B>
      <key>value</key>
      <key>value</key>
    </B>
  </BList>
</A>

我想将xml解组为A类。我使用的是@XmlAnyElement。当我使用大尺寸XML Blist.size=100000解组A时,性能并不理想。我该怎么做才能提高性能?

1 个答案:

答案 0 :(得分:0)

根据您的说明,这是一个XML代码段:

<doc>
  <data>
    <someKey>someValue</someKey>
    <otherKey>otherValue</otherKey>
  </data>
</doc>

这是数据类型的类:

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MappingType", propOrder = {
    "any"
})
public class MappingType {

    @XmlAnyElement(lax = true)
    protected List<Object> any;

    public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }
}

解组:

void unmarshal() throws Exception {
    JAXBContext jc = JAXBContext.newInstance( PACKAGE );
    Unmarshaller m = jc.createUnmarshaller();
    JAXBElement<?> obj = (JAXBElement<?>)m.unmarshal( new File( XMLIN ) );
    DocType dt = (DocType)obj.getValue();
    MappingType mt = dt.getData();
    for( Object elobj: mt.getAny() ){
        System.out.println( "object: " + elobj.getClass() );
    }
    System.out.println( "done" );
}

输出

object: class com.sun.org.apache.xerces.internal.dom.ElementNSImpl
object: class com.sun.org.apache.xerces.internal.dom.ElementNSImpl
done

处理DOM元素取决于您,但您还能期待什么呢?