日期:2014-05-20  浏览次数:20853 次

百分相送:大唐电信笔试上机题(关于SAX解析XML的)大家试试!
用SAX解析下列XML:

<?xml   version= "1.0 "?>
<in>
    <sheader>
        <mac> </mac>
        <MACInstNo> 9850 </MACInstNo>
        <PINSeed> </PINSeed>
        <SrcChnlNo> 850 </SrcChnlNo>
        <ChkFlag> </ChkFlag>
        <CombFlag> </CombFlag>
        <HostServ> waiwei_02 </HostServ>
    </sheader>
    <tpheader>
        <TermId> </TermId>
        <InstNo> 3500 </InstNo>
        <TlrNo> 901004 </TlrNo>
    </tpheader>
    <tdheader>
        <TranCode> 7703 </TranCode>
        <TermJourNo> 000850326665 </TermJourNo>
        <TermDate> 20070706 </TermDate>
        <AuthTlrNo> </AuthTlrNo>
        <AuthPIN> </AuthPIN>
        <AuthCardFlag> </AuthCardFlag>
        <AuthCardSeq> </AuthCardSeq>
    </tdheader>
    <tin>
        <Type> 1 </Type>
        <mobileNum> 123456 </mobileNum>
        <Mode> 1 </Mode>  
    </tin>
</in>
        解析结果为一个Map,key是xml中元素的全路径,value是元素的值,例如:
in.sheader.MACInstNo   =   9850

------解决方案--------------------
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.parsers.ParserConfigurationException;
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 SAXTest extends DefaultHandler{

  private static Map <String, String> map = new TreeMap <String, String> ();
  private String curKey = " ";
  private String key = " ";
  private String value = " ";

  public static void main(String[] args) throws ParserConfigurationException,
      SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    parser.parse(new File( "a.xml "), new SAXTest());
    
    // 输出 map
    for(Map.Entry <String, String> entry : map.entrySet()) {
      System.out.println(entry.getKey() + " --> " + entry.getValue());
    }
  }

  public void startElement(String namespaceURI, String localName,
      String qName, Attributes attributes) throws SAXException {
    if (key.length() == 0) {
      key = qName;
    } else {
      key = key + ". " + qName;
    }
    curKey = qName;
  }

  public void endElement(String uri, String localName, String qName)
      throws SAXException {
    if (key.contains( ". ")) {
      if (curKey.equals(qName)) {