Nic*_*ick 21 java validation dtd jaxb
我正在尝试使用JAXB取消一些我首先使用xjc创建的XML.我不想做就解组任何验证,但即使我已经停用根据与JAXB文档验证u.setSchema(null);,但这并没有阻止了FileNotFoundException,当它试图运行,并不能找到的模式被抛出.
JAXBContext jc = JAXBContext.newInstance("blast");
Unmarshaller u = jc.createUnmarshaller();
u.setSchema(null);
return u.unmarshal(blast)
Run Code Online (Sandbox Code Playgroud)
我已经看到类似的问题,通过设置apache属性http://apache.org/xml/features/validation/schema来禁用SAX解析验证false,但是我无法让Unmarshaller使用我自己的sax解析器.
Ren*_*aud 17
基于@ blaise-doughan和@aerobiotic的答案,这是一个对我有用的解决方案:
import java.io.FileReader;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
public class Demo2 {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyBean.class);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
spf.setFeature("http://xml.org/sax/features/validation", false);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
InputSource inputSource = new InputSource(
new FileReader("myfile.xml"));
SAXSource source = new SAXSource(xmlReader, inputSource);
Unmarshaller unmarshaller = jc.createUnmarshaller();
MyBean foo = (MyBean) unmarshaller.unmarshal(source);
}
}
Run Code Online (Sandbox Code Playgroud)
下面的示例代码演示了如何使用JAXB(JSR-222)实现来使用SAX解析器:
import java.io.FileReader;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
InputSource inputSource = new InputSource(new FileReader("input.xml"));
SAXSource source = new SAXSource(xmlReader, inputSource);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Foo foo = (Foo) unmarshaller.unmarshal(source);
System.out.println(foo.getValue());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17813 次 |
| 最近记录: |