Skip to content

Instantly share code, notes, and snippets.

@tdoly
Created December 27, 2013 09:02
Show Gist options
  • Save tdoly/8144372 to your computer and use it in GitHub Desktop.
Save tdoly/8144372 to your computer and use it in GitHub Desktop.
java using sax get xml node and nodeValue
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserXmlUtil extends DefaultHandler {
private StringBuffer node=new StringBuffer();
private StringBuffer nodeValue=new StringBuffer();
private StringBuffer value=new StringBuffer();
public String getNode() {
return node.toString();
}
public String getNodeValue() {
return nodeValue.toString();
}
/*
* 此方法有三个参数 ch是传回来的字符数组,其包含元素内容 start和length分别是数组的开始位置和结束位置
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String content=new String(ch, start, length);
value.append(content);
super.characters(ch, start, length);
}
@Override
public void startDocument() throws SAXException {
// System.out.println("Start");
super.startDocument();
}
@Override
public void endDocument() throws SAXException {
// System.out.println("End");
node.append("\n");
nodeValue.append("\n");
super.endDocument();
}
/*
* uri是名称空间 localName是包含名称空间的标签,如果没有名称空间,则为空 qName是不包含名称空间的标签 attributes是属性的集合
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// System.out.println("starttag:" + qName);
value=new StringBuffer();
if(!"ROOT".equals(qName)) {
node.append(qName).append(",");
}
if(attributes != null) {
for(int i=0; i < attributes.getLength(); i++) {
// getQName()是获取属性名称,
System.out.println(attributes.getQName(i) + "=\"" + attributes.getValue(i) + "\"");
}
}
super.startElement(uri, localName, qName, attributes);
}
/*
* uri是名称空间 localName是包含名称空间的标签,如果没有名称空间,则为空 qName是不包含名称空间的标签
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// System.out.println(value.toString());
// System.out.println("endtag:" + qName);
if(!"ROOT".equals(qName)) {
nodeValue.append(value.toString()).append(",");
}
super.endElement(uri, localName, qName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment