如何从xml中的html表中获取表数据?

时间:2013-01-25 08:05:35

标签: html r xml-parsing html-table

我有一个xml文件,其中包含一些html内容,如粗体,段落和表格。我编写了shell脚本来解析除表之外的所有html标签。我正在使用XML(R包)来解析数据。

<Root>
    <Title> This is dummy xml file </Title>
    <Content> This table summarises data in BMC format.
        <div class="abctable">
            <table border="1" cellspacing="0" cellpadding="0" width="100%"   class="coder">
                <tbody>
                    <tr>
                        <th width="50%">ABC</th>
                        <th width="50%">Weight status</th>
                    </tr>
                    <tr>
                        <td>are 18.5</td>
                        <td>arew</td>
                    </tr>
                    <tr>
                        <td>18.5 &amp;mdash; 24.9</td>
                        <td>rweq</td>
                    </tr>
                    <tr>
                        <td>25.0 &amp;mdash; 29.9</td>
                        <td>qewrte</td>
                    </tr>
                    <tr>
                        <td>30.0 and hwerqer</td>
                        <td>rwqe</td>
                    </tr>
                    <tr>
                        <td>40.0 rweq rweq</td>
                        <td>rqwe reqw</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </Content>
    <Section>blah blah blah</Section>
</Root>

如何解析xml中现有的这个表的内容?

2 个答案:

答案 0 :(得分:2)

readHTMLTable包中有一个名为XML的函数,它似乎可以满足您的需求吗?

以下是使用以下xml文件执行此操作的方法:

<Root>
    <Title> This is dummy xml file </Title>
    <Content>
      This table summarises data in BMC format.

     <div class="abctable">
     <table border="1" cellspacing="0" cellpadding="0" width="100%"   class="coder">
   <tbody>
   <tr>
       <th width="50%">ABC</th><th width="50%">Weight status</th>
   </tr>
   <tr>
       <td>are 18.5</td>
       <td>arew</td>
   </tr>
   <tr>
       <td>18.5 &amp;mdash; 24.9</td>
       <td>rweq</td>
   </tr>
   <tr>
       <td>25.0 &amp;mdash; 29.9</td>
       <td>qewrte</td>
   </tr>
   <tr>
       <td>30.0 and hwerqer</td>
       <td>rwqe</td>
   </tr>
   <tr>
       <td>40.0 rweq rweq</td>
       <td>rqwe reqw</td>
   </tr>
   </tbody>
  </table>
   </Content>
 </div>
 <Section>blah blah blah</Section>
 </Root>

如果将其保存在名为/tmp/data.xml的文件中,则可以使用以下代码:

doc <- htmlParse("/tmp/data.xml")
tableNodes <- getNodeSet(doc, "//table")
tb <- readHTMLTable(tableNodes[[1]])

哪五个人:

R> tb
                 V1            V2
1               ABC Weight status
2          are 18.5          arew
3 18.5 &mdash; 24.9          rweq
4 25.0 &mdash; 29.9        qewrte
5  30.0 and hwerqer          rwqe
6    40.0 rweq rweq     rqwe reqw

答案 1 :(得分:1)

xml解析的最佳方法是使用xpath表达式

Xpath Tutorial

Xpath and R

How to use XPath and R stackoverflow