Sharon Kasis
Sharon Kasis

Reputation: 123

How can i parse only the text from a single html line?

I have this line:

<a  onmouseover="EnterContent('ToolTip','לחיילים ולתושבי הדרום באהבה','<u><span style=color:#000099;>כתב: רוטרית   בתאריך: 22.07.14  שעה: 08:56</span></u><br>המון רצון לעזור, להתנדב, להעניק, לפנק, לאהוב, ולחבק קיים היום בעם.<br>נצלו אשכול זה לפרסם דברים שיוכלו לעזור לחיילים ולתושבי הדרום.<br><br>חיילים, ותו...'); Activate();" onmouseout="deActivate()" href="javascript:void(0)"> 

From this line i need to get only the hebrew words. To remove all tags and the onmouseover and tooltip and void and only to be left with the words in hebrew and the part: בתאריך: 22.07.14 שעה: 08:56

Or in this case :

<a  onmouseover="EnterContent('ToolTip','אין לדווח בפורום על תנועת כוחות, סדרי כוחות, פעילות מבצעית וכל דיווח המסכן חיי חיילים','<u><span style=color:#000099;>כתב: מובחר   בתאריך: 17.07.14  שעה: 23:20</span></u><br>[anchor:אשכול עוגן מתאריך  17.07.14 בשעה  23:20  על-ידי  Maya, (גלובל)]במסגרת הכניסה הקרקעית במבצע צוק איתן, ההנהלה פונה אליכם ומבקשת בכל לשון של בקשה...'); Activate();" onmouseout="deActivate()" href="javascript:void(0)"> 

Again to be left with all hebrew words and: מתאריך 17.07.14 בשעה  23:20

How can i do it ?

I have this method i used to parse text:

public List<string> CreateTextList(string filePath)
        {
            List<string> text = new List<string>();
            var htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.OptionFixNestedTags = true;
            htmlDoc.Load(filePath, System.Text.Encoding.GetEncoding(65001));

            if (htmlDoc.DocumentNode != null)
            {
                var nodes = htmlDoc.DocumentNode.SelectNodes("//a/b");
                foreach (var node in nodes)
                {
                    text.Add(node.InnerText);

                }
            }
            text = Filters.filterNumbers(text);
            return text;
        }

It's working good but it's getting file not lines/text.

Upvotes: 0

Views: 123

Answers (2)

MaPi
MaPi

Reputation: 1601

Well, you can't use an XML parser if you work with lines (you can't traverse the XML tree structure if you don't have the whole structure).

But as suggested here: https://stackoverflow.com/a/19524158/1648371

You can use

string noHTML = Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim();

For retrieving the strings instead of replacing the HTML characters with an empty space, you can replace them with a special character that you won't have in your input (like the Swedish letter å) and then

Regex.Matches(noHTML, "å", RegexOptions.IgnoreCase))

Upvotes: 1

Alberto
Alberto

Reputation: 15941

Instead of HtmlDocument.Load(string path) use the method HtmlDocument.LoadHtml(string html):

string html = "<a  onmouseover=\"EnterContent('ToolTip....";
var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(html);

Upvotes: 1

Related Questions