mybatis-XPathParser作用

XPathParser 是用來解析xml文件的 包括檢測xml文件格式


public class XPathParser {



private Document document;// 用來解析xml文件
private boolean validation;//驗證
private EntityResolver entityResolver;//通過key查找dtd文件
private Properties variables;
private XPath xpath;//將元素轉換成爲節點信息


public XPathParser(InputStream inputStream, boolean validation,
Properties variables, EntityResolver entityResolver) {
commonConstructor(validation, variables, entityResolver);
this.document = createDocument(new InputSource(inputStream));
}


private void commonConstructor(boolean validation, Properties variables,
EntityResolver entityResolver) {
this.validation = validation;
this.entityResolver = entityResolver;
this.variables = variables;
XPathFactory factory = XPathFactory.newInstance();
this.xpath = factory.newXPath();
}


/**
* 將xml數據源解析成Document對象

* @param inputSource
* @return
*/
private Document createDocument(InputSource inputSource) {
// important: this must only be called AFTER common constructor
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
/**
* 以下幾個參數有什麼好的用處不知道 先把網上的解釋抄下來
*/
// factory.setValidating(validation);// 指定由此代碼生成的解析器將驗證被解析的文檔


factory.setNamespaceAware(false);// 指定由此代碼生成的解析器將提供對 XML 名稱空間的支持。
factory.setIgnoringComments(true);// 指定由此代碼生成的解析器將忽略註釋。
factory.setIgnoringElementContentWhitespace(false);// 指定由此工廠創建的解析器在解析
// XML
// 文檔時,必須刪除元素內容中的空格
factory.setCoalescing(false);// 指定由此代碼生成的解析器將把 CDATA 節點轉換爲 Text
// 節點,並將其附加到相鄰(如果有)的 Text 節點。
factory.setExpandEntityReferences(true);// 指定由此代碼產生的解析器將擴展實體引用節點


DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(entityResolver);
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException exception)
throws SAXException {
throw exception;
}


@Override
public void fatalError(SAXParseException exception)
throws SAXException {
throw exception;
}


@Override
public void warning(SAXParseException exception)
throws SAXException {
}
});
return builder.parse(inputSource);
} catch (Exception e) {
throw new BuilderException(
"Error creating document instance.  Cause: " + e, e);
}
}


public XNode evalNode(String expression) {
return evalNode(document, expression);
}


public XNode evalNode(Object root, String expression) {
Node node = (Node) evaluate(expression, root, XPathConstants.NODE);
if (node == null) {
return null;
}
return new XNode(this, node, variables);
}


private Object evaluate(String expression, Object root, QName returnType) {
try {
return xpath.evaluate(expression, root, returnType);
} catch (Exception e) {
throw new BuilderException("Error evaluating XPath.  Cause: " + e,
e);
}
}


public void setVariables(Properties variables) {
this.variables = variables;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章