XMLBeam是POJO解封器(通过XPath)的不错的XML,但是它仅允许您配置DocumentBuilder或DocumentBuilderFactory。
TagSoup是一个不错的SAX解析器,它使您可以将讨厌的HTML文档解析为XML。
我想将TagSoup用作XMLBeam的XML解析器,以便可以使用XPath将讨厌的HTML解组到POJO。
有没有一种方法可以转换或包装SAX解析器,以便可以将其用作DocumentBuilder或DocumentBuilderFactory?
最佳答案
您可以将SAX包装在DocumentBuilder中。 XMLBeam仅使用DocumentBuilder的parse(InputSource)方法,因此非常简单:
import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.xml.sax.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;
import java.io.IOException;
public class MyDocumentBuilder extends DocumentBuilder {
@Override
public Document parse(InputSource inputSource) throws SAXException, IOException {
XMLReader xmlReader = new Parser();
xmlReader.setFeature(Parser.namespacesFeature, false);
xmlReader.setFeature(Parser.namespacePrefixesFeature, false);
try{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult domResult = new DOMResult();
transformer.transform(new SAXSource(xmlReader, inputSource), domResult);
return (Document) domResult.getNode();
}
catch(Exception exp){
throw new RuntimeException("Error parsing with Tagsoup");
}
}
@Override
public void setErrorHandler(ErrorHandler errorHandler) {
}
@Override
public Document newDocument() {
return null;
}
@Override
public void setEntityResolver(EntityResolver entityResolver) {
}
@Override
public boolean isValidating() {
return false;
}
@Override
public DOMImplementation getDOMImplementation() {
return null;
}
@Override
public boolean isNamespaceAware() {
return false;
}
}
然后,在其他地方,您可以告诉XMLBeam使用您的DocumentBuilder:
XMLFactoriesConfig xmlFactoriesConfig = new DefaultXMLFactoriesConfig(){
@Override
public DocumentBuilder createDocumentBuilder() {
return new MyDocumentBuilder();
}
};
XBProjector xbProjector = new XBProjector(xmlFactoriesConfig);