【问题标题】:Extract xml data from gzip file using apache tika?使用 apache tika 从 gzip 文件中提取 xml 数据?
【发布时间】:2011-03-30 14:55:51
【问题描述】:

我正在做一个项目,我需要使用 apache tika[AM NEW TO TIKA] 从 gz 文件中提取 xml(站点地图)数据。 fie 名称类似于 sitemap01.xml.gz 我可以从普通文本文件或 html 中提取数据,但我不知道如何从 gz 中提取 xml 并从 xml 中提取元数据和数据... 过去两天我在 Google 上搜索过。

我需要在 tika 中使用 delegateParser 从 xml 中提取数据吗? 请指导我一些示例或文章....

这是我的尝试

public void parseXml() throws IOException{
    Metadata metadata = new Metadata();
    ContentHandler handler = new BodyContentHandler();
    Parser parser = new AutoDetectParser();
    ParseContext context = new ParseContext();
     InputStream stream =this.getClass().getResourceAsStream("sitemap.xml.gz");
    try {
        parser.parse(stream,handler,metadata,context);
        for(int i = 0; i <metadata.names().length; i++) {
            String name = metadata.names()[i];
            System.out.println(name + " : " + metadata.get(name));
          }
        System.out.println(handler.toString());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TikaException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
         if(stream!=null) {
                stream.close();
            }
    }


}

【问题讨论】:

    标签: apache gzip apache-tika


    【解决方案1】:

    您缺少的是在 ParseContext 上设置递归解析器。你可能想要这样的东西:

    Parser parser = new AutoDetectParser();
    ParseContext context = new ParseContext();
    context.set(Parser.class, parser);
    parser.parse(....)
    

    通过在 ParseContext 上设置 Parser,您可以告诉 Tika 在遇到嵌入文档(例如 GZip 中的 XML)时调用它

    【讨论】:

      【解决方案2】:

      以下是针对您的案例使用 Apache Tika 的 XML 解析器的方法:

       //detecting the file type
        BodyContentHandler handler = new BodyContentHandler(-1);
        Metadata metadata = new Metadata();
        File inFile = new File("sitemap.xml.gz");
        System.out.println(inFile.isFile());
        FileInputStream inputstream = new FileInputStream(inFile);
        ParseContext pcontext = new ParseContext();
      
        //Xml parser
        XMLParser xmlparser = new XMLParser(); 
        xmlparser.parse(inputstream, handler, metadata, pcontext);
        System.out.println(pcontext.toString());
      
        System.out.println("Contents of the document:" + handler.toString());//this one contains all contents from xml files and tags are also removed
        System.out.println("Metadata of the document:");
        String[] metadataNames = metadata.names();
      
        for(String name : metadataNames) {
          System.out.println(name + ": " + metadata.get(name));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多