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