以下是从XML文档中提取内容和元数据的程序 :
import java.io.File;import java.io.FileInputStream;import java.io.IOException;import org.apache.tika.exception.TikaException;import org.apache.tika.metadata.Metadata;import org.apache.tika.parser.ParseContext;import org.apache.tika.parser.xml.XMLParser;import org.apache.tika.sax.BodyContentHandler;import org.xml.sax.SAXException;public class XmlParse { public static void main(final String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File("pom.xml")); ParseContext pcontext = new ParseContext(); //Xml parser XMLParser xmlparser = new XMLParser(); xmlparser.parse(inputstream, handler, metadata, pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + ": " + metadata.get(name)); } }}
将上述代码保存为 XmlParse.java ,使用以下命令从命令提示符编译它 :
javac XmlParse.javajava XmlParse
以下是example.xml文件的快照
此文档具有以下属性 :
如果您执行上述程序,它将为您提供以下输出 :
输出 :
Contents of the document: 4.0.0org.apache.tikatika1.6org.apache.tikatika-core1.6org.apache.tikatika-parsers1.6srcmaven-compiler-plugin3.11.71.7Metadata of the document:Content-Type: application/xml