这是我要解析的xml文件数据。我想得到最后一个标签,即<RECEIPTNO>
的内容。有人可以帮忙吗?
<MSPDB><COMPANYNO>01</COMPANYNO><SALESPERSON>01101</SALESPERSON><MAPNO>5</MAPNO><CUSTOMERNO>1</CUSTOMERNO><ORDERNO>1</ORDERNO><QUOTENO>1</QUOTENO><LASTINVOICENO>1</LASTINVOICENO><RECEIPTNO>8</RECEIPTNO></MSPDB>
以下是我尝试使用SAX解析器的代码。
String FILE_NAME = "Mspdb.xml";
File file=new File(Supporter.getAppCommonPath(),FILE_NAME);
FileInputStream stream;
try {
stream = new FileInputStream(file);
String[] result=parseDocument(stream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public String[] parseDocument(InputStream stream)
{
String[] resultArray=new String[8];
String result="";
SAXParserFactory parserFactory=SAXParserFactory.newInstance();
try {
SAXParser parser=parserFactory.newSAXParser();
XMLReader reader=parser.getXMLReader();
Xmlhandler handler=new Xmlhandler();
reader.setContentHandler(handler);
InputSource inputSource = new InputSource();
inputSource.setEncoding("UTF-8");
inputSource.setByteStream(stream);
reader.parse(inputSource);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result=resultArray[7];
return resultArray;
}
class Xmlhandler extends DefaultHandler
{
private String tempVal;
private String receiptNo;
private String value;
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
value="";
tempVal="";
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("Value:" + tempVal);
System.out.println("End:" + localName);
if(localName.equalsIgnoreCase("RECEIPTNO"))
{
receiptNo=tempVal;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
value=new String(ch, start, length);
tempVal=value+tempVal;
}
}