6

解组 XML 文件后,作为 XML 文件中属性的所有属性的值都为 NULL(fileDateTime、fileId 等...)

我真的不明白为什么,因为我有正确的注释@XmlAttribute(name = "FileDateTime")@XmlAttribute(name = "FileId")

如您所见,我不使用任何命名空间(所以我认为不是命名空间问题!)

我正在使用 JDK 1.6、Sax 2.0.1 和 XercesImpl 2.9.1

谢谢你的帮助。

测试.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...

解析方法(解组和 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);
4

1 回答 1

8

解决

似乎 JAXB 不能与 SAX 解析器一起正常工作,除非解析器设置为可识别名称空间。

刚刚添加了这一行,它工作正常

saxParserFactory.setNamespaceAware(true);
于 2013-04-12T12:08:32.840 回答