解组XML文件后,XML文件中属性的所有属性的值都为NULL(fileDateTime,fileId等等)
我真的不明白为什么我有正确的注释@XmlAttribute(name = "FileDateTime")
和@XmlAttribute(name = "FileId")
正如您所看到的,我不使用任何命名空间(因此我认为不是命名空间问题!)
我正在使用JDK 1.6,Sax 2.0.1和XercesImpl 2.9.1
感谢您的帮助。
的test.xml
<KeyImport_file FileDateTime="2013-05-30T09:00:00" FileId="KeyImport_source_20121231124500">
<!--1 or more repetitions:-->
<record record_number="10">
...
</record>
</KeyImport_file>
KeyImportFile.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"record"
})
@XmlRootElement(name = "KeyImport_file")
public class KeyImportFile {
@XmlElement(required = true)
protected List<KeyImportFile.Record> record;
@XmlAttribute(name = "FileDateTime")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar fileDateTime;
@XmlAttribute(name = "FileId")
protected String fileId;
etc...
etc...
解析方法(unmarshal&amp; XSD验证):
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.UnmarshallerHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.InputStream;
private KeyImportFile parseXML(final InputStream xmlInputStream, final StreamSource xsdSource)
throws Exception
{
KeyImportFile keyImportFile;
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdSource);
JAXBContext jc = JAXBContext.newInstance(KeyImportFile.class);
UnmarshallerHandler unmarshallerHandler = jc.createUnmarshaller().getUnmarshallerHandler();
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setSchema(schema);
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(unmarshallerHandler);
xmlReader.setErrorHandler(keyImportErrorHandler);
InputSource inputSource = new InputSource(xmlInputStream);
xmlReader.parse(inputSource);
xmlInputStream.close();
keyImportFile = (KeyImportFile) unmarshallerHandler.getResult();
return keyImportFile;
}
编辑
只需更改我的解析方法而不使用sax就可以了。知道为什么吗?我想使用sax和jabx来解决性能问题。
KeyImportFile keyImportFile;
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdSource);
JAXBContext jc = JAXBContext.newInstance(KeyImportFile.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
keyImportFile = (KeyImportFile) unmarshaller.unmarshal(xmlInputStream);
答案 0 :(得分:7)
<强>解决强>
似乎JAXB无法正常使用SAX解析器,除非将解析器设置为名称空间感知。
刚添加此行并且工作正常
saxParserFactory.setNamespaceAware(true);