我想问你一个关于xml文件的问题。我想通过使用Java中的SAX解析器来检查xml标签是否具有属性。
有答案吗?请帮助我...
最佳答案
SaxParser 处理程序的 startElement
方法有一个参数,用于保存与其关联的属性列表。你可以信赖这一点。例如,该程序打印出所有带有属性的标签以及与其关联的属性名称。
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class FindTagWithAttributes {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if(attributes != null && attributes.getLength() > 0){
System.out.print(qName + " tag has attributes - ");
for(int i=0; i<attributes.getLength(); i++){
System.out.println(attributes.getLocalName(i));
}
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
public void characters(char ch[], int start, int length)
throws SAXException {
}
};
saxParser.parse("data.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于java - 如何使用Java中的SAX解析器检查xml标签是否具有属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949139/