Extract value from input element string array - c#

i have an string array read from <td> of a datatable like this
"<input id=\"item_Job_ID\" name=\"item.Job_ID\" type=\"text\" value=\"5036\">"
how can i get only the value from it in c#.
i tried Split("\\") which doesn't work. can i use linq to extract the value ?
Thank You in Advance

I think, It's work for you
string inputstr = "< input id =\"item_Job_ID\" name=\"item.Job_ID\" type=\"text\" value=\"5036\">";
var splitdataList = inputstr.Split(new string[] { "\"", "=", " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
var value = splitdataList.Contains("value") ? splitdataList[splitdataList.IndexOf("value") + 1] : ""; // Return 5036

use Html Agility Pack.
HtmlDocument doc = new HtmlDocument();
string htmlContent = "<input id=\"item_Job_ID\" name=\"item.Job_ID\" type=\"text\" value=\"5036\">";
doc.LoadHtml(htmlContent);
HtmlNode inputNode = doc.DocumentNode.FirstChild;
string value = inputNode.GetAttributeValue("value", "0");

Related

C# creating an HTML line with escaping

I'm creating a loop in which each line is a pretty long HTML line on the page. I've tried various combinations of # and """ but I just can't seem to get the hang of it
This is what I've got now, but the single quotes are giving me problems on the page, so I want to change all the single quotes to double quotes, just like a normal HTML line would use them for properties in the elements:
sOutput += "<div class='item link-item " + starOrBullet + "'><a href='" + appSet + linkID + "&TabID=" + tabID + "' target=’_blank’>" + linkText + "</a></div>";
variables are:
starOrBullet
appSet
LinkID
tabID (NOT $TabID=)
linkText
BTW, appSet="http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID="
Can someone help me here?
You have to escape the double quotes (") with \"
For your case:
sOutput += "<div class=\"item link-item " + starOrBullet + "\"><a href=\"" + appSet + linkID + "&TabID=" + tabID + "\" target=’_blank’>" + linkText + "</a></div>";
If you concat many strings, you should use StringBuilder for performance reasons.
You can use a verbatim string and escape a double quote with a double quote. So it will be a double double quote.
tring mystring = #"This is \t a ""verbatim"" string";
You can also make your string shorter by doing the following:
Method 1
string mystring = #"First Line
Second Line
Third Line";
Method 2
string mystring = "First Line \n" +
"Second Line \n" +
"Third Line \n";
Method 3
var mystring = String.Join(
Environment.NewLine,
"First Line",
"Second Line",
"Third Line");
You must make habit to use C# class to generate Html instead concatenation. Please find below code to generate Html using C#.
Check this link for more information
https://dejanstojanovic.net/aspnet/2014/june/generating-html-string-in-c/
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.htmltextwriter
Find below code for your question
protected void Page_Load(object sender, EventArgs e)
{
string starOrBullet = "star-link";
string appSet = "http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID=";
string LinkID = "2";
string tabID = "1";
string linkText = "linkText_Here";
string sOutput = string.Empty;
StringBuilder sbControlHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
{
//Generate container div control
HtmlGenericControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("class", string.Format("item link-item {0}",starOrBullet));
//Generate link control
HtmlGenericControl linkControl = new HtmlGenericControl("a");
linkControl.Attributes.Add("href", string.Format("{0}{1}&TabID={2}",appSet,LinkID,tabID));
linkControl.Attributes.Add("target", "_blank");
linkControl.InnerText = linkText;
//Add linkControl to container div
divControl.Controls.Add(linkControl);
//Generate HTML string and dispose object
divControl.RenderControl(htmlWriter);
sbControlHtml.Append(stringWriter.ToString());
divControl.Dispose();
}
}
sOutput = sbControlHtml.ToString();
}

Error with regex Input string was not in a correct format

Hi guys I have string <span class="lnk">Участники <span class="clgry">59728</span></span>
I parse it
string population = Regex.Match(content, #"Участники <span class=""clgry"">(?<id>[^""]+?)</span>").Groups["id"].Value;
int j = 0;
if (!string.IsNullOrEmpty(population))
{
log("[+] Группа: " + group + " Учасники: " + population + "\r\n");
int population_int = Convert.ToInt32(population);
if (population_int > 20000)
{
lock (accslocker)
{
StreamWriter file = new StreamWriter("opened.txt", true);
file.Write(group + ":" + population + "\r\n");
file.Close();
}
j++;
}
}
But when my string is ><span class="lnk">Участники <span class="clgry"></span></span> I receive an exaption "Input string was not in a correct format".
How to avoid it?
Instead of Regex use a real html parser to parse htmls. (for ex, HtmlAgilityPack)
string html = #"<span class=""lnk"">Участники <span class=""clgry"">59728</span>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var list = doc.DocumentNode.SelectNodes("//span[#class='lnk']/span[#class='clgry']")
.Select(x => new
{
ParentText = x.ParentNode.FirstChild.InnerText,
Text = x.InnerText
})
.ToList();
Trying to parse html content with regex is not a good decision. See this. Use Html Agliliy Pack instead.
var spans = doc.DocumentNode.Descendants("span")
.Where(s => s.Attributes["class"].Value == "clgry")
.Select(x => x.InnerText)
.ToList();

Want to assign HTML value to String variable

I want to assign HTML snippet to string variable.
something like -
string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello'
Please suggest.
string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello
var doc = new XmlDocument();
doc.LoadXml(div);
string text = doc.InnerText;
Do you also need the Jquery version of this?
If you are sure that the HTML won't change between the string you want to get, you can simply do a Substring between the two constants string and you will get your string into your variable.
const string prefix = "<table>";
const string suffix = "</table>";
string s = prefix + "TEST" + suffix ;
string s2 = s.Substring(prefix.Length, s.IndexOf(suffix, StringComparison.Ordinal) - prefix.Length);
Here is the Regex version:
const string prefix = "<table>";
const string suffix = "</table>";
string s = prefix + "TEST" + suffix;
string s2 = Regex.Match(s, prefix + "(.*)" + suffix).Groups[1].Value;

How to parse the text out of html in c#

I have an html expression like this:
"This is <h4>Some</h4> Text" + Environment.NewLine +
"This is some more <h5>text</h5>
And I want only to extract the text. So the result should be
"This is Some Text" + Environment.NewLine +
"This is some more text"
How do I do this?
Use HtmlAgilityPack
string html = #"This is <h4>Some</h4> Text" + Environment.NewLine +
"This is some more <h5>text</h5>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var str = doc.DocumentNode.InnerText;
Simple using regex: Regex.Replace(source, "<.*?>", string.Empty);

String from codebehind to array in Javascript

Hi all i have code that reads from a DB and populates a string in the code behind
List<string> rows = new List<string>();
DataTable prods = common.GetDataTable("vStoreProduct", new string[] { "stpt_Name" }, "stpt_CompanyId = " + company.CompanyId.ToString() + " AND stpt_Deleted is null");
foreach (DataRow row in prods.Rows)
{
prodNames += "\"" + row["stpt_Name"].ToString().Trim() + "\",";
}
string cleanedNanes = prodNames.Substring(0, prodNames.Length - 1);
prodNames = "[" + cleanedNanes + "]";
This produces something like ["Test1","Test2"]
In javascript i have
var availableTags = '<% =prodNames %>';
alert(availableTags);
How can i access this like an array in javascript like
alert(availableTags[5]);
and get the full item at the given index.
Thanks any help would be great
Get rid of the quotes:
var availableTags = <% =prodNames %>;
With the quotes there, you're creating a JavaScript string. Without them, you've got a JavaScript array constant.
You're going to have to split the variable from .NET into a JS array.
Check out: http://www.w3schools.com/jsref/jsref_split.asp
Example based on your code:
var availableTags = '<% =prodNames %>';
var mySplitResult = availableTags .split(",");
alert(mySplitResult[1]);
I believe split() will do what you want:
var availableTagsResult = availableTags.split(",");
alert(availableTagsResult[1]) //Display element 1
This will create an array from the string which has been split on ,

Categories