如何在React Native中解析HTML文件?

时间:2016-07-13 06:17:57

标签: javascript html react-native html-parsing

如何从文件系统中获取HTML文件并从中解析特定元素。

例如,给定下面的html片段,我如何提取表格内容并进行渲染?

<html>
<div>
  <h1>header</h1>
  <table id="a" border="1">
    <th>Number</th>
    <th>content A</th>
    <th>contetn A</th>
    <th>content A</th>
    <tr>
      <td>1</td>
      <td>a</td>
      <td>a</td>
      <td>a</td>
    </tr>
    <th>Number</th>
    <th>content B</th>
    <th>content B</th>
    <th>content B</th>

    <tr>
      <td>1</td>
      <td>b</td>
      <td>b</td>
      <td>b</td>
    </tr>
  </table>
</div>
<br>
<footer>footer</footer>

</html>

3 个答案:

答案 0 :(得分:1)

只需使用fetch()下载HTML,使用fast-html-parser解析,将结果写入状态并使用WebView呈现该状态

答案 1 :(得分:0)

使用fetch()获取html并使用react-native-html-parser进行解析,使用WebView进行处理和显示。

import DOMParser from 'react-native-html-parser';

fetch('http://www.google.com').then((response) => {
   const html = response.text();    
   const parser = new DOMParser.DOMParser();
   const parsed = parser.parseFromString(html, 'text/html');
   parsed.getElementsByAttribute('class', 'b');
});

P.S。来自其他答案的fast-html-parser对我来说并不起作用。在使用react-native 0.54进行安装时,我遇到了多个错误。

答案 2 :(得分:0)

我建议使用以下库:react-native-htmlviewer。它需要html并将其呈现为本机视图。您还可以自定义元素的呈现方式。

// only render the <table> nodes in your html
function renderNode(node, index, siblings, parent, defaultRenderer) {
  if (node.name !== 'table'){
    return (
      <View key={index}>
        {defaultRenderer(node.children, parent)}
      </View>
    )l
  }

}

// your html
const htmlContent = `<html></html>`;

class App extends React.Component {
  render() {
    return (
      <HTMLView value={htmlContent} renderNode={renderNode} />
    );
  }
}
相关问题