2012-12-11 67 views
1

我想解析下面的文件。我想打印每位乘客的身份和姓名。你能給我解析它的代碼嗎?如何用Java和SAX解析我的簡單XML文件?

<?xml version="1.0" encoding="utf-8"?> 
<root xmlns:android="www.google.com"> 

<passenger id = "001"> 
<name>Tom Cruise</name> 
</passenger> 

<passenger id = "002"> 
<name>Tom Hanks</name> 
</passenger> 

</root> 

UPDATE 這是我試過。碼,問題等這裏所說的 - Error in output of a simple SAX parser

+0

嘗試使用'javax.xml.parsers.DocumentBuilder'和'org.w3c.dom.Document'類,然後在遇到一些問題時共享代碼。 –

+0

那麼,這是我試過的,我沒有得到一個答案,導致我在正確的方向 - http://stackoverflow.com/questions/13798038/error-in-output-of-a-simple-sax-parser –

+0

試圖通過逆向工程學習。 –

回答

2

這裏是一個工作示例開始,但我建議你使用StAX的相反,你會看到,SAX是不是很方便

import java.io.File; 
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 SAX2 { 

    public static void main(String[] args) throws Exception { 
     SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); 
     parser.parse(new File("test.xml"), new DefaultHandler() { 

      @Override 
      public void startElement(String uri, String localName, 
        String qName, Attributes atts) throws SAXException { 
       if (qName.equals("passenger")) { 
        System.out.println("id = " + atts.getValue(0)); 
       } 
      } 

      @Override 
      public void endElement(String uri, String localName, String qName) 
        throws SAXException { 
      } 

      @Override 
      public void characters(char[] ch, int start, int length) 
        throws SAXException { 
       String text = new String(ch, start, length); 
       if (!text.trim().isEmpty()) { 
        System.out.println("name " + text); 
       } 
      } 
     }); 
    } 
} 

輸出

id = 001 
name Tom Cruise 
id = 002 
name Tom Hanks 
0
SAXParserFactory factory = SAXParserFactory.newInstance(); 
try { 

    InputStream xmlInput = new FileInputStream("theFile.xml"); 
    SAXParser  saxParser = factory.newSAXParser(); 

    DefaultHandler handler = new SaxHandler(); 
    saxParser.parse(xmlInput, handler); 

} catch (Throwable err) { 
    err.printStackTrace(); 
} 
0
String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + 
         "<root xmlns:android=\"www.google.com\">" + 
          "<passenger id = \"001\">" + 
           "<name>Tom Cruise</name>" + 
          "</passenger>" + 
          "<passenger id = \"002\">" + 
           "<name>Tom Hanks</name>" + 
          "</passenger>" + 
         "</root>"; 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      InputSource is = new InputSource(new StringReader(str)); 

      final Document document = db.parse(is); 

      System.out.println("node Name " + document.getChildNodes().item(0).getChildNodes().item(1).getNodeName());