CachedExpr의 모든 XPath와 변수를 한 번에로드하여 여러 번 사용하려고합니다. 누구나 CachedExpr에서 변수와 XPath를 추가 할 수있는 샘플을 제공 할 수 있으며 XPathNamespace를 선언하는 방법을 알려줍니다.VTD-xml 파서에 CachedExpr을 구현하는 방법
public class VTDParser {
private final CustomAutoPilot autoPilot;
public static class CustomAutoPilot extends com.ximpleware.AutoPilot {
final Hashtable<String, com.ximpleware.Expr> variables = new Hashtable<>();
public CustomAutoPilot() {
super();
}
public CustomAutoPilot(VTDNav v) {
super(v);
}
public void declareVariableExpr(String varName, String varExpr) throws XPathParseException {
try {
parser p = new parser(new StringReader(varExpr));
p.nsHash = nsHash;
p.symbolHash = variables;
xpe = (com.ximpleware.Expr) p.parse().value;
variables.put(varName, xpe);
ft = true;
} catch (XPathParseException e) {
throw e;
} catch (Exception e) {
throw new XPathParseException("Error occurred");
}
}
@Override
public void selectXPath(String s) throws XPathParseException {
try {
parser p = new parser(new StringReader(s));
p.nsHash = nsHash;
p.symbolHash = variables;
xpe = (com.ximpleware.Expr) p.parse().value;
ft = true;
if (enableCaching)
xpe.markCacheable();
} catch (XPathParseException e) {
throw e;
} catch (Exception e) {
throw new XPathParseException("");
}
}
public VTDNav getNavigationObject() {
return vn;
}
}
public VTDParser(String message) throws ParseException {
try {
VTDGen vg = new VTDGen();
byte[] content = message.getBytes(Charset.defaultCharset());
vg.setDoc(content);
vg.parse(true);
VTDNav vn = vg.getNav();
autoPilot = new CustomAutoPilot(vn);
autoPilot.declareXPathNameSpace("prefix", "http://www.w3.org");
} catch (ParseException e) {
throw e;
}
}
public String asString(String xpath) throws XPathParseException {
try {
autoPilot.selectXPath(xpath);
return autoPilot.evalXPathToString().trim();
} catch (XPathParseException e) {
throw e;
}
}
public void variable(String name, String value) throws XPathParseException {
try {
autoPilot.declareVariableExpr(name, value);
} catch (XPathParseException e) {
throw e;
}
}
public static void main(String[] args) throws ParseException, XPathParseException {
String xml = "<tree><fruit> Mango</fruit></tree>";
VTDParser parser = new VTDParser(xml);
System.out.println(parser.asString("//tree/fruit"));
}
} 우리는 성공적으로 구문 분석됩니다 CustomAutopilot 클래스 썼다
. 우리는 CachedExpr에서 xpath 목록을 컴파일하고 매번 컴파일하는 대신 재사용합니다.
CachedExpr은 사용자가 직접 상호 작용하는 것으로 생각하지 않습니다 ... 일단 켜져 있으면 (기본적으로) 사용자가 기본적으로 지정한대로 작동합니다 ... XPathNamespace는 AutoPilot으로 선언됩니다 ... 일반 xpath 평가와 같습니다 ... –