使用HtmlParser解析HTML (C#版)

來源:互聯網
上載者:User

如果要對HTML進行解析,提取HTML的資料或者修改HTML資料,HtmlParser是一個不錯的選擇.

使用HtmlParser可以解析本地和網路上的HTML資料:

Parser parser = new Parser( new Winista.Text.HtmlParser.Http.HttpProtocol(new Uri("uriString")));

Parser parser = new Parser( new Winista.Text.HtmlParser.Lex.Lexer( "HtmlString" ) );

System.IO.Stream stream = new System.IO.FileStream( "filePath" , System.IO.FileMode.Open );

Parser parser = new Parser( new Winista.Text.HtmlParser.Lex.Lexer( new Winista.Text.HtmlParser.Lex.Page ( stream ,"charSet") ) );還可以分析某些特定節點的資料,使用 NodeClassFilter 指定要分析的節點類型:

NodeFilter filter = new NodeClassFilter( typeof( Winista.Text.HtmlParser.Tags.Div ) );使用Parser執行個體的Parse方法可以獲得節點數組

NodeList nodeList = parser.Parse( null );

NodeList nodeList = parser.Parse( filter);現在分析一下的一段HTML:

<div class="divCss" id="div_1">

     <div name="div" class="divCss" id="div_2">div_2</div>

     <table name="table" id="table_1">

         <tr>

             <td>HtmlParser</td>

             <td><div id="div_3"><font color="red">HtmlParser</font></div></td>

         </tr>

     </table>

</div>

txtResult是顯示分析處理後的資料,txtSource是讀取HTML資料的文字框

//記錄個節點的起始位置,避免重複處理

     IList<int> start = new List<int>( );

     protected void Button1_Click ( object sender , EventArgs e )

     {

         this.txtResult.Text = string.Empty;

         Lexer lexer = new Lexer( this.txtSource.Text );

         Parser parser = new Parser( lexer );

         NodeFilter filter = new NodeClassFilter( typeof( Winista.Text.HtmlParser.Tags.Div ) );

        NodeList nodeList = parser.Parse( null );

         if ( nodeList.Count == 0 )

             txtResult.Text = "沒有符合要求的節點";

         else

         {

             for ( int i = 0 ; i < nodeList.Count ; i++ )

             {

                 paserData( nodeList[i] );

             }

         }

     }

     private ITag getTag ( INode node )

     {

         if ( node == null )

             return null;

        return   node is ITag   ? node as ITag :   null;

     }

     private void paserData ( INode node)

     {

         ITag tag = getTag( node );

         if ( tag != null && !tag.IsEndTag( ) && !start.Contains(tag.StartPosition))

         {

             object oId = tag.GetAttribute( "ID" );

             object oName = tag.GetAttribute( "name" );

             object oClass = tag.GetAttribute( "class" );

             this.txtResult.Text += tag.TagName + ":\r\nID:" + oId + " Name:" + oName+ " Class:" + oClass + " StartPosition:" + tag.StartPosition.ToString( ) + "\r\n";

             start.Add( tag.StartPosition );

         }

         //子節點

         if ( node.Children != null && node.Children.Count > 0 )

         {

             paserData( node.FirstChild );

         }

         //兄弟節點

         INode siblingNode = node.NextSibling;

         while ( siblingNode != null )

         {

             paserData( siblingNode );

             siblingNode = siblingNode.NextSibling;

         }

     }txtResult顯示的資料為:

DIV:

ID:div_1 Name: Class:divCss StartPosition:0

DIV:

ID:div_2 Name:div Class:divCss StartPosition:34

TABLE:

ID:table_1 Name:table Class: StartPosition:90

TR:

ID: Name: Class: StartPosition:127

TD:

ID: Name: Class: StartPosition:136

TD:

ID: Name: Class: StartPosition:160

DIV:

ID:div_3 Name: Class: StartPosition:164

FONT:

ID: Name: Class: StartPosition:180

HtmlParser將我們指定的資料給分析出來了,現在來對要分析的資料進行一些修改:給沒有name和class屬性的指定屬性:

            object oId = tag.GetAttribute( "ID" );

             object oName = tag.GetAttribute( "name" );

             object oClass = tag.GetAttribute( "class" );

             if ( oName == null )

           {

                 oName = "name";

                 tag.SetAttribute( "name" , oName.ToString( ) );

             }

             if ( oClass == null )

             {

                 oClass = "class";

                 tag.SetAttribute( "name" , oClass.ToString( ) );

             }

             this.txtResult.Text += tag.TagName + ":\r\nID:" + oId + " Name:" + oName

                    + " Class:" + oClass + " StartPosition:" + tag.StartPosition.ToString( ) + "\r\n";

             start.Add( tag.StartPosition );txtResult顯示的資料為:

DIV:

ID:div_1 Name:name Class:divCss StartPosition:0

DIV:

ID:div_2 Name:div Class:divCss StartPosition:34

TABLE:

ID:table_1 Name:table Class:class StartPosition:90

TR:

ID: Name:name Class:class StartPosition:127

TD:

ID: Name:name Class:class StartPosition:136

TD:

ID: Name:name Class:class StartPosition:160

DIV:

ID:div_3 Name:name Class:class StartPosition:164

FONT:

ID: Name:name Class:class StartPosition:180

HtmlParser實現了我們的目的,現在在給節點為DIV並且ID為div_3的節點添加一個子節點:

             object oId = tag.GetAttribute( "ID" );

             object oName = tag.GetAttribute( "name" );

             object oClass = tag.GetAttribute( "class" );

if ( tag.TagName == "DIV" && tag.GetAttribute( "ID" ) == "div_3" )

             {

                 INode newNode = new TextNode( "add a new node" );

                 tag.Children.Add( newNode );

             }

             this.txtResult.Text += tag.TagName + ":\r\nID:" + oId + " Name:" + oName

                    + " Class:" + oClass + " StartPosition:" + tag.StartPosition.ToString( ) + "\r\n";輸出nodeList[0].ToHtml( ):

<div class="divCss" id="div_1">

     <div name="div" class="divCss" id="div_2">div_2</div>

     <table name="table" id="table_1">

         <tr>

             <td>HtmlParser</td>

             <td><div id="div_3"><font color="red">HtmlParser</font>add a new node</div></td>

         </tr>

     </table>

</div>id為div_3的div節點後面加上了要添加的資料.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.