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"));
}
相關部分