JAXB 有多灵活? [英] How flexible is JAXB?
问题描述
我正在考虑使用 JAXB 进行 XML 解析,但到目前为止我遇到了几个问题,这让我相信它可能不够灵活,无法满足我的需求.
I am considering using JAXB for XML parsing but I'm having a couple of issues so far that lead me to believe that it might not be flexible enough for what I want.
我将解析第三方提供的 XML 以符合我将发布的 XSD.所以我想要足够灵活来处理没有命名空间的文件或指定命名空间的旧版本并且实际上可能包含无效元素.
I'll be parsing XML that is provided by third parties to conform to an XSD that I'll publish. So I want to be flexible enough to handle files that don't have namespaces or specify an old version of the namespace and may in fact contain invalid elements.
JAXB 是否可以实现这种灵活性?目前,如果未提供命名空间,则无法解析.
Is this sort of flexibility possible with JAXB? At the moment it fails to parse if the namespace is not provided.
推荐答案
JAXB 的灵活性如何?
How flexible is JAXB?
非常
所以我想要足够灵活来处理没有名称空间或指定名称空间的旧版本,实际上可能包含无效元素.
So I want to be flexible enough to handle files that don't have namespaces or specify an old version of the namespace and may in fact contain invalid elements.
命名空间过滤器
下面是一个 SAX XmlFilter
,可用于应用缺失的命名空间.
Below is a SAX XmlFilter
that can be used to apply a missing namespace.
import org.xml.sax.*;
import org.xml.sax.helpers.XMLFilterImpl;
public class NamespaceFilter extends XMLFilterImpl {
private static final String NAMESPACE = "http://www.example.com/customer";
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(NAMESPACE, localName, qName);
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
super.startElement(NAMESPACE, localName, qName, atts);
}
}
演示
下面是一个示例,说明如何将 SAX XMLFilter
与 JAXB 一起应用.
Below is an example of how you can apply the SAX XMLFilter
with JAXB.
import javax.xml.bind.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
public class Demo {
public static void main(String[] args) throws Exception {
// Create the JAXBContext
JAXBContext jc = JAXBContext.newInstance(Customer.class);
// Create the XMLFilter
XMLFilter filter = new NamespaceFilter();
// Set the parent XMLReader on the XMLFilter
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
filter.setParent(xr);
// Set UnmarshallerHandler as ContentHandler on XMLFilter
Unmarshaller unmarshaller = jc.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = unmarshaller
.getUnmarshallerHandler();
filter.setContentHandler(unmarshallerHandler);
// Parse the XML
InputSource xml = new InputSource("src/blog/namespace/sax/input.xml");
filter.parse(xml);
Customer customer = (Customer) unmarshallerHandler.getResult();
}
}
了解更多信息
这篇关于JAXB 有多灵活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!