【问题标题】:HTML table to java objectHTML 表到 java 对象
【发布时间】:2018-07-26 16:17:54
【问题描述】:

我需要将 html 表转换为 java 对象。现在我找不到任何好的方法来实现这个任务。表格示例如下:

<table id='table'>
  <tr>
    <th>name</th>
    <th>address</th>
  </tr>
  <tr>
    <td>
      <a href=''>name1</a>
    </td>
    <td>
      <a href=''>Address</a>
    </td>
  </tr>
 </table>

我还希望将表映射到下一个对象:

public class myClass {
    public String name;
    public String address;
}

如果有人帮助我完成这项任务,我将非常感激。

【问题讨论】:

  • 我不太明白,能否详细说明。你想用字段名称和地址制作一个表对象吗?所以Table { Table(name, address){this.name, this.address;} }等(对不起格式化)
  • 我用对象结构更新了问题。
  • 更好,但仍有一些松散的地方。您是否尝试使用 JSP?您是否尝试解析表格内容的 html 文档并使用它来为您的对象的成员提供种子?
  • 我没有尝试使用jsp。应用程序只需要解析和转换静态html文件。

标签: java html xml parsing xml-parsing


【解决方案1】:

我认为在您的情况下,您想使用Jsoup,这是一个用于解析网页的不错的 Java 库。一旦你使用 Jsoup 的选择器从网页解析了你想要的数据,用它创建一个 Java 对象应该是不平凡的。以下是一些有用的链接:

文件输入 = new File("table.html");

Document doc = Jsoup.parse(input, "UTF-8", "http://somewebsite.com/");

Elements row1name = doc.select("tr"); 

Elements row1address = doc.select("tr");

MyClass table1 = new MyClass(row1name, row1address);

类似的东西(选择器用于 row1name 和地址是错误的,您必须查看文档以验证正确的方法......我不记得了)。我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我的答案可能对这个问题的作者没有用(我迟到了 3 年,所以我猜这不是正确的时机),但我认为它可能对可能遇到这个答案的许多其他开发人员有用。

    今天,我刚刚(以我公司的名义)发布了一个 HTML 到 POJO 的完整框架,您可以使用它将 HTML 映射到任何 POJO 类,只需一些注释。该库本身非常方便,并且具有许多其他功能,同时非常易于插入。你可以在这里看看:https://github.com/whimtrip/jwht-htmltopojo

    如何使用:基础知识

    假设我们需要解析以下 html 页面:

    <html>
        <head>
            <title>A Simple HTML Document</title>
        </head>
        <body>
            <div class="restaurant">
                <h1>A la bonne Franquette</h1>
                <p>French cuisine restaurant for gourmet of fellow french people</p>
                <div class="location">
                    <p>in <span>London</span></p>
                </div>
                <p>Restaurant n*18,190. Ranked 113 out of 1,550 restaurants</p>  
                <div class="meals">
                    <div class="meal">
                        <p>Veal Cutlet</p>
                        <p rating-color="green">4.5/5 stars</p>
                        <p>Chef Mr. Frenchie</p>
                    </div>
    
                    <div class="meal">
                        <p>Ratatouille</p>
                        <p rating-color="orange">3.6/5 stars</p>
                        <p>Chef Mr. Frenchie and Mme. French-Cuisine</p>
                    </div>
    
                </div> 
            </div>    
        </body>
    </html>
    

    让我们创建我们想要映射到的 POJO:

    public class Restaurant {
    
        @Selector( value = "div.restaurant > h1")
        private String name;
    
        @Selector( value = "div.restaurant > p:nth-child(2)")
        private String description;
    
        @Selector( value = "div.restaurant > div:nth-child(3) > p > span")    
        private String location;    
    
        @Selector( 
            value = "div.restaurant > p:nth-child(4)"
            format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
            indexForRegexPattern = 1,
            useDeserializer = true,
            deserializer = ReplacerDeserializer.class,
            preConvert = true,
            postConvert = false
        )
        // so that the number becomes a valid number as they are shown in this format : 18,190
        @ReplaceWith(value = ",", with = "")
        private Long id;
    
        @Selector( 
            value = "div.restaurant > p:nth-child(4)"
            format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
            // This time, we want the second regex group and not the first one anymore
            indexForRegexPattern = 2,
            useDeserializer = true,
            deserializer = ReplacerDeserializer.class,
            preConvert = true,
            postConvert = false
        )
        // so that the number becomes a valid number as they are shown in this format : 18,190
        @ReplaceWith(value = ",", with = "")
        private Integer rank;
    
        @Selector(value = ".meal")    
        private List<Meal> meals;
    
        // getters and setters
    
    }
    

    现在还有Meal 类:

    public class Meal {
    
        @Selector(value = "p:nth-child(1)")
        private String name;
    
        @Selector(
            value = "p:nth-child(2)",
            format = "^([0-9.]+)\/5 stars$",
            indexForRegexPattern = 1
        )
        private Float stars;
    
        @Selector(
            value = "p:nth-child(2)",
            // rating-color custom attribute can be used as well
            attr = "rating-color"
        )
        private String ratingColor;
    
        @Selector(
            value = "p:nth-child(3)"
        )
        private String chefs;
    
        // getters and setters.
    }
    

    我们在 github 页面上对上述代码提供了更多解释。

    目前,让我们看看如何废弃它。

    private static final String MY_HTML_FILE = "my-html-file.html";
    
    public static void main(String[] args) {
    
    
        HtmlToPojoEngine htmlToPojoEngine = HtmlToPojoEngine.create();
    
        HtmlAdapter<Restaurant> adapter = htmlToPojoEngine.adapter(Restaurant.class);
    
        // If they were several restaurants in the same page, 
        // you would need to create a parent POJO containing
        // a list of Restaurants as shown with the meals here
        Restaurant restaurant = adapter.fromHtml(getHtmlBody());
    
        // That's it, do some magic now!
    
    }
    
    
    private static String getHtmlBody() throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(MY_HTML_FILE));
        return new String(encoded, Charset.forName("UTF-8"));
    
    }
    

    另一个简短的例子可以找到here

    希望这会对那里的人有所帮助!

    【讨论】:

    • 非常感谢您的回答! =)
    • 不客气!很高兴与任何对此感兴趣的人分享这个项目!也欢迎任何反馈:)
    • @Louis-wht 您开发的框架非常有用。非常感谢。
    【解决方案3】:

    其中一个解决方案是使用 XSLT。因此,要将 html 数据序列化为 java 对象,您可以按照以下步骤操作::

    • 使用 XSLT 规则将 HTML 转换为 XML 文档。
    • 将 XML 反序列化为 java 对象。

    如果您的 html 页面有未闭合的标签,则此解决方案不起作用,因此您需要在第一步之前使用一些验证库。在你的 html 无效的情况下,Jsoup 更容​​易使用,@coderrick 在another 回答中描述了如何使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 2021-10-21
      • 2019-12-23
      • 2013-03-31
      • 2022-01-14
      相关资源
      最近更新 更多