2014-10-20 83 views
0

我是一名新程序員,我遇到了一個我正在開發的項目。我正在嘗試使用Saxparser解析xml文件,而不是獲取用戶輸入。我的XML文件有多種類型的「引用」,如書籍,期刊文章分機。我無法通過解析xml來填充對象層次結構,我有適當的類與它們各自的構造函數以及getter和setter方法來創建對象。我唯一的問題是如何通過在我的主類中重寫下面的這些方法來解析時創建這些對象。從xml解析創建對象

 public class main extends DefaultHandler{ 

      @Override 
      public void startElement(String s, String s1, String tagname, Attributes attr) throws SAXException{ 
      if(tagname.equals("Book")){ 
      } 

      } 

      @Override 
      public void characters(char [] ac, int i, int s)throws SAXException{ 

      } 

      @Override 
      public void endElement(String s, String s1, String tag)throws SAXException{ 

      } 


      public static void main(String[] args) throws IOException,  ParserConfigurationException, SAXException { 
      // Create scanner 
      Scanner OswegoNote = new Scanner(System.in); 
      //Create a parser factory 
      SAXParserFactory factory = SAXParserFactory.newInstance(); 
      //make the parser 
      SAXParser saxParser = factory.newSAXParser(); 
      XMLReader parser = saxParser.getXMLReader(); 
      //create a handler 
      main handler = new main(); 
      //tell the parser to use the handler 
      parser.setContentHandler(handler); 
      //Read and parse the document 
      parser.parse("xmlFile.xml"); 

下面是我試圖解析和檢索每個引用類型的顯示值的xml文件的一部分。

 <Citation> 
       <Book> 
       <Name>A Wavelet Tour of Signal Processing</Name> 
       <Publisher>Academic Press</Publisher> 
       <PublicationDate>01/01/2009</PublicationDate> 
       <PublicationPlace>Burlington,MA</PublicationPlace> 
       <Authors> 
       <author>Stephanie M Mallot</author> 
       </Authors> 
       <Keywords> 
       <Keyword>DSP</Keyword> 
       <Keyword>Wavelets</Keyword> 
       <Keyword>Sparse Data</Keyword> 
       </Keywords> 
      </Book> 
     </Citation> 


     <Citation> 
      <JournalArticle> 
       <Name>The attractions of stupidity</Name> 
       <TitleOfJournal>The St. Croix Review</TitleOfJournal> 
       <PublicationDate>October, 2002</PublicationDate> 
       <volNumber>30</volNumber> 
       <IssueNumber>2</IssueNumber> 
      <Authors> 
       <author>Harry Hank Hirsh</author> 
       <author>Mark Harold Coen</author> 
       <author>Michael Charles Mozer</author> 
      </Authors> 
       <Pages StartPage="6" EndPage="10"/> 
      <Keywords> 
       <Keyword>Psychology</Keyword> 
      <Keyword>Sociology</Keyword> 
      <Keyword>Intelligence</Keyword> 
      <Keyword>Sexuality</Keyword> 
      </Keywords> 
     </JournalArticle> 
     </Citation> 
+0

我真的推薦看看JAXB(http://www.vogella.com/tutorials/JAXB/article.html),這也是一個標準。 – lexicore 2014-10-20 07:01:53

回答

0

在表示對象的startElement事件處啓動對象的內部數據模型。在程序中爲變量/數據結構中的對象累加數據。當您到達該對象的endElement時,使用您存儲的數據來構造/配置對象。

如果對象可以嵌套,則可能需要維護上下文堆棧。如果它們以其他方式相關,則可能必須將ID和IDREF映射到對這些對象的引用。

許多例子可以在網上找到。存在幾個相互競爭的半標準表示,加上一大堆定製方法。