C#中HTML/XML處理及Regex

來源:互聯網
上載者:User

標籤:c#   xml   html   Regex   

HTML Parser
一個比較方便的html解析package是HtmlAgilityPack,可以按照如顯示在Visual Studio中安裝。

使用該包的一個簡單一實例代碼如下:

        public static bool CrawlCategoryReviewInfo(string categoryUrl)        {            var resp = HttpUtils.GetResponseData(categoryUrl);            if (resp == null)            {                logger.Info("Failed to request the category page from Suning server!");                return false;            }            HtmlDocument document = new HtmlDocument();            document.LoadHtml(resp);            HtmlNodeCollection collection = document.DocumentNode.SelectNodes("//div[@id=‘productTab‘]//li[contains(@class,‘item‘)]");            if (collection == null || collection.Count < 1) return false;            foreach(HtmlNode prod in collection)            {                if (prod == null || prod.Attributes["name"] == null) continue;                string prodId = prod.Attributes["name"].Value;                if(prodId.StartsWith("000000000")) prodId = prodId.Substring(9);                HtmlNode commentNode = prod.SelectSingleNode(".//a[contains(@name,‘comment‘)]/i");                if (commentNode == null) continue;                int commentCount = int.Parse(commentNode.InnerText);                Console.WriteLine(prodId + "\t" + commentCount);            }            if (collection.Count < int.Parse(ConfigurationManager.AppSettings["CAT_PAGE_ITEM_NUM"]))                return false;            return true;        }

需要特別注意的是,對於在HtmlNode內部找子HtmlNode所寫的xpath,xpath需要在前面加上”.”,如上面的”.//a[contains(@name,’comment’)]/i”,否則可能會發現找的是全域的Node。

XML DOM
系統空間System.Xml.Linq中的XDocument可以協助解析或者輸出XML檔案。
1) 載入解析XML:

            var filePath = Path.Combine(path, "image_status.xml");            XDocument doc = XDocument.Load(filePath);            var pics = doc.Descendants("pic");            foreach (var pic in pics)            {                string url = (string)pic.Element("url");                string imgFile = (string)pic.Element("file");                processedImages.Add(url, imgFile);            }

2) 儲存產生XML

            var filePath = Path.Combine(path, "image_status.xml");            var docUpdate = new XElement("status");            foreach (var tuple in processedImages)            {                var item = new XElement("image");                item.Add(new XElement("url", tuple.Key));                item.Add(new XElement("file", tuple.Value));                docUpdate.Add(item);            }            docUpdate.Save(filePath);

Regex抽取
利用Regex來抽取資訊,其實不同語言的邏輯都一樣,文法略有不同。這裡不做介紹,僅僅給出一個抽取的例子作為參考。注意每一個匹配部分會用”?<—>”開頭來對該Group命名,後面取匹配的資料的時候就可以藉助這個名字得到相應的匹配值。

        public static void CrawlProductReviewInfo()        {            string resp = "satisfy({\"reviewCounts\":[{\"oneStarCount\":2,\"twoStarCount\":0,\"threeStarCount\":23,\"fourStarCount\":43,\"fiveStarCount\":431,\"againCount\":4,\"bestCount\":0,\"picFlagCount\":5,\"totalCount\":499,\"qualityStar\":4.8}],\"returnCode\":\"1\",\"returnMsg\":\"成功擷取評價個數\"})";            Regex revRegex = new Regex("\"totalCount\":(?<comment>.*?),\"qualityStar\":(?<score>.*?)}");             MatchCollection mc = revRegex.Matches(resp);            if (mc.Count > 0)            {                var comment = decimal.Parse(mc[0].Groups["comment"].Value);                var score = decimal.Parse(mc[0].Groups["score"].Value);            }        }

C#中HTML/XML處理及Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.