java - JTidy java API toConvert HTML to XHTML

标签 java html xhtml jtidy

我正在使用 JTidy 将 HTML 转换为 XHTML,但我在我的 XHTML 文件中发现了这个标记  。 我可以阻止它吗?
这是我的代码

    //from html to xhtml
   try   
    {  
        fis = new FileInputStream(htmlFileName);  
    }  
    catch (java.io.FileNotFoundException e)   
    {  
        System.out.println("File not found: " + htmlFileName);  
    }  
        Tidy tidy = new Tidy(); 
        tidy.setShowWarnings(false);
        tidy.setXmlTags(false);
        tidy.setInputEncoding("UTF-8");
        tidy.setOutputEncoding("UTF-8");
        tidy.setXHTML(true);// 
        tidy.setMakeClean(true);
        Document xmlDoc = tidy.parseDOM(fis, null);  
    try  
    {  
        tidy.pprint(xmlDoc,new FileOutputStream("c.xhtml"));  
    }  
    catch(Exception e)  
    {  
    }

最佳答案

只有当输入也被视为 XML 时,我才成功。所以要么将 xmltags 设置为 true

 tidy.setXmlTags(true);

并接受错误和警告或进行两次转换。 第一次转换以清理 html(html 到 xhtml),第二次从 xhtml 转换为带有设置 xmltags 的 xhtml,因此不会出现错误和警告。

        String htmlFileName = "test.html";
    try( InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(htmlFileName);
         FileOutputStream fos = new FileOutputStream("tmp.xhtml");) {
        Tidy tidy = new Tidy();
        tidy.setShowWarnings(true);
        tidy.setInputEncoding("UTF-8");
        tidy.setOutputEncoding("UTF-8");
        tidy.setXHTML(true);
        tidy.setMakeClean(true);
        Document xmlDoc = tidy.parseDOM(in, fos);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try( InputStream in = new FileInputStream("tmp.xhtml");
         FileOutputStream fos = new FileOutputStream("c.xhtml");) {
        Tidy tidy = new Tidy();
        tidy.setShowWarnings(true);
        tidy.setXmlTags(true);
        tidy.setInputEncoding("UTF-8");
        tidy.setOutputEncoding("UTF-8");
        tidy.setXHTML(true);
        tidy.setMakeClean(true);
        Document xmlDoc = tidy.parseDOM(in, null);
        tidy.pprint(xmlDoc, fos);
    } catch (Exception e) {
        e.printStackTrace();
    }

我用的是最新的jtidy 938版本

关于java - JTidy java API toConvert HTML to XHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15063870/

相关文章:

html - 你如何制作 :visited bold in XHTML/CSS?

java - connect() 方法忽略其超时值

java - JSonParser 出现空值

java - 链表排序错误

javascript - HTML 到 PHP 中数组内部的数组

xhtml - XHTML 1.0 Transitional vs XHTML 1.0严格?

java - 这个maven认证错误表示什么?

javascript - Html5 Canvas + Fabric.js 独立堆肥

javascript - 使用图片上传的django动态背景

html - 地址信息有哪些 HTML 标记?