是否可以通过SAX读取给定XML中<xsd:appinfo>
标记中存储的值。目前我正在使用DefaultHandler类的自定义实现来读取XML中的元素和值。我现在需要阅读存储在<xsd:appinfo>
标记中的其他信息。
我正在尝试针对XSD架构验证XML。我使用SAX来使用下面的代码验证架构
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory
.newInstance("http://www.w3.org/2001/XMLSchema");
SAXParser parser = null;
try {
factory.setSchema(schemaFactory
.newSchema(new Source[] { new StreamSource(xsd) }));
parser = factory.newSAXParser();
} catch (SAXException se) {
System.out.println("SCHEMA : " + se.getMessage()); // problem in
// the XSD
// itself
isInvalid=true;
}
XMLReader reader = parser.getXMLReader();
final MyContentHandler xpathTracker = new MyContentHandler();
reader.setContentHandler(xpathTracker);
reader.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
System.out.println("WARNING: " + e.getMessage());
// do nothing
}
public void error(SAXParseException e) throws SAXException {
xpathError.add(xpathTracker.getXPath());
}
我有ContentHandler的以下代码
public class MyContentHandler extends XMLFilterImpl {
private final Stack<StackElement> stackElements = new Stack<StackElement>();
public MyContentHandler() {
super();
}
public MyContentHandler(XMLReader parent) {
super(parent);
}
public MyContentHandler(ContentHandler contentHandler) {
setContentHandler(contentHandler);
}
public void startDocument() throws SAXException {
super.startDocument();
stackElements.clear();
stackElements.push(new StackElement());
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
//add new element to stack
stackElements.push(new StackElement());
stackElements.peek().update(uri,localName,qName);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
stackElements.pop();
}
public String getCurrentElement(){
return stackElements.peek().getCurrent();
}
/**
* Gets the XPath to the current element.
*/
public String getXPath() {
StringBuilder buf = new StringBuilder();
for (StackElement h : stackElements) {
h.appendPath(buf);
}
return buf.toString();
}
}
这个想法是,如果任何元素的XSD验证失败,我需要报告该元素的完整XPATH。上面的代码和DefaultHandler就是这样做的。现在我的要求是,除了报告XPATH之外,它还应该打印出一个错误代码,该代码作为<xsd:appinfo>
的一部分提供。下面是XSD的片段。
<xsd:element minOccurs="1" name="seqid" type="nonEmptyString">
<xsd:annotation>
<xsd:appinfo>ERROR_CODE="ERR_123</xsd:appinfo>
</xsd:annotation>