在xml时一般我们会加上xsd等约束和命名空间,加上了有时会导致jaxb读取xml报错,众里寻他千百度,那人却在灯火阑珊处,经过一番苦寻找到了解决方法,忽略命名空间的方式读取xml,实例代码如下:
package xxx;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.sax.SAXSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;
public class XmlOperator {
/**
* 读取XML-可配置忽略命名空间
*
* @param file XML文件
* @param type 类型
* @param <T> 数据类型
* @param ignoreNamespace 解析时是否忽略命名空间
* @return 数据对象
* @author chang.xu
*/
@SuppressWarnings("unchecked")
public <T> T readXml(final File file, final Class<T> type, final boolean ignoreNamespace) {
T objResult = null;
FileInputStream fis = null;
try {
JAXBContext context = JAXBContext.newInstance(type);
Unmarshaller unmarshaller = context.createUnmarshaller();
XMLReader reader = XMLReaderFactory.createXMLReader();
XMLFilterImpl nsfFilter = new XMLFilterImpl() {
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts)
throws SAXException {
String strURI = uri;
if (ignoreNamespace) {
strURI = "";
}
super.startElement(strURI, localName, qName, atts);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String strURI = uri;
if (ignoreNamespace) {
strURI = "";
}
super.endElement(strURI, localName, localName);
}
@Override
public void startPrefixMapping(String prefix, String url) throws SAXException {
super.startPrefixMapping(prefix, url);
}
};
fis = new FileInputStream(file);
nsfFilter.setParent(reader);
InputSource input = new InputSource(fis);
SAXSource source = new SAXSource(nsfFilter, input);
objResult = (T) unmarshaller.unmarshal(source);
} catch (JAXBException | SAXException | FileNotFoundException e) {
LOG.error("读取文件数据出错!file:" + file.getPath() + " type:" + type, e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
LOG.error("文件流关闭异常:" + e.getMessage(), e);
}
}
}
return objResult;
}
}