2011-02-10 87 views
2

我們需要使用Java從給定文本文檔中獲取樹狀結構。使用的文件類型應該是通用的並且打開(rtf,odt,...)。目前我們使用Apache Tika從多個文檔中解析純文本。使用Java解析文檔結構

我們應該使用哪種文件類型和API,以便我們能夠最可靠地獲得正確的結構解析?如果Tika可以做到這一點,我會很高興看到任何示範。

例如,我們應該得到這種從給定的文檔數據:

Main Heading 
    Heading 1 
    Heading 1.1 
    Heading 2 
    Heading 2.2 

主標題是文章的標題。論文有兩個主要標題,標題1和標題2,它們都有一個小標題。我們還應該在每個標題下(段落文本)獲取內容。

任何幫助表示讚賞。

回答

3

OpenDocument(.odt)實際上是一個包含多個xml文件的zip包。 Content.xml包含文檔的實際文本內容。我們對標題感興趣,他們可以在文本中找到:h標籤。閱讀更多關於ODT

我發現了一個用於從QueryPath從.odt文件中提取標題的實現。

由於原來的問題是關於Java的,在這裏。首先,我們需要使用ZipFile訪問content.xml。然後我們使用SAX解析content.xml中的xml內容。示例代碼簡單地打印出所有的標題:

Test3.odt 
content.xml 
3764 
1 My New Great Paper 
2 Abstract 
2 Introduction 
2 Content 
3 More content 
3 Even more 
2 Conclusions 

示例代碼:

 @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { temp = ""; if("text:h".equals(qName)) { String headingLevel = atts.getValue("text:outline-level"); if(headingLevel != null) { System.out.print(headingLevel + " "); } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { char[] subArray = new char[length]; System.arraycopy(ch, start, subArray, 0, length); temp = new String(subArray); fullText.append(temp); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("text:h".equals(qName)) { System.out.println(temp); } } 
:像這樣使用的ContentHandler的

 public void printHeadingsOfOdtFIle(File odtFile) { 

    try { 

     ZipFile zFile = new ZipFile(odtFile); 
     System.out.println(zFile.getName()); 

     ZipEntry contentFile = zFile.getEntry("content.xml"); 

     System.out.println(contentFile.getName()); 
     System.out.println(contentFile.getSize()); 
     XMLReader xr = XMLReaderFactory.createXMLReader(); 
     OdtDocumentContentHandler handler = new OdtDocumentContentHandler(); 
     xr.setContentHandler(handler); 

     xr.parse(new InputSource(zFile.getInputStream(contentFile))); 

    } catch (Exception e) { 

     e.printStackTrace(); 

    } 

} 

public static void main(String[] args) { 

    new OdtDocumentStructureExtractor().printHeadingsOfOdtFIle(new File("Test3.odt")); 

} 

相關部分