我正在寻找一个合适的解析器来解析给定的XML。我想解析整个XML只有当标签- 'employee',属性- 'validated=false'否则停止解析。如何使用SAX、STAX或任何其他解析器执行条件XML解析?
<?xml version="1.0"?>
<database>
<employee validated="False">
<name>Lars </name>
<street validated="False"> Test </street>
<telephone number= "0123"/>
</employee>
<employee validated="True">
<name>Baegs </name>
<street validated="True"> Test </street>
<telephone number= "0123"/>
</employee>
</database>
我尝试了下面的SAX解析器代码
List<XmlObjects> xmlObjects;
String espXmlFileName;
String tmpValue;
XmlObjects xmlObjectsTmp;
public SaxParser(String espXmlFileName) {
this.espXmlFileName = espXmlFileName;
xmlObjects = new ArrayList<XmlObjects>();
parseDocument();
printDatas();
}
private void printDatas() {
for (XmlObjects tmpB : xmlObjects) {
System.out.println(tmpB.toString());
}
}
private void parseDocument() {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(espXmlFileName, this);
} catch (ParserConfigurationException e) {
System.out.println("ParserConfig error");
} catch (SAXException e) {
System.out.println("SAXException : xml not well formed");
} catch (IOException e) {
System.out.println("IO error");
}
}
public void startElement(String uri, String localName, String qName,
org.xml.sax.Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("employee")) {
String value1 = attributes.getValue("validated");
if (value1.equalsIgnoreCase("FALSE")) {
if (qName.equalsIgnoreCase("name")) {
String value2 = attributes.getValue("validated");
xmlObjectsTmp.setName(attributes
.getValue("name"));
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("employee")) {
xmlObjects.add(xmlObjectsTmp);
}
if (qName.equalsIgnoreCase("name")) {
xmlObjectsTmp.setName(tmpValue);
}
}
public static void main(String argv[]) {
new SaxParser("C:\xml\xml2.xml");
}
在ContentHandler
的startElement
方法中,当您的validated
属性具有值True
时,您可以简单地抛出SAXException
以中止解析。
@Override
public void startElement(final String uri, final String localName,
final String qName, final Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase("employee") || localName.equalsIgnoreCase("street")) {
final String validated = attributes.getValue("validated");
if(validated != null && !validated.equals("False")) {
throw new SAXException(localName + " has already been validated");
} else {
//your processing logic here
}
}
}
如果你愿意,你可以注册一个ErrorHandler来用你自己的方式处理这个错误。