我从Mysql获取数据,但问题是" HTML标记,即
<p>LARGE</p><p>Lamb;<br>;li;ul;
也正在获取我的数据,我只需要&#34; LARGE&#34;和&#34; Lamb&#34;从上面。如何从String中分离/删除HTML标记?
答案 0 :(得分:2)
我将假设HTML完好无损,可能如下所示:
<ul><li><p>LARGE</p><p>Lamb<br></li></ul>
在这种情况下,我会使用HtmlAgilityPack来获取内容,而不必使用正则表达式。
var html = "<ul><li><p>LARGE</p><p>Lamb</p><br></li></ul> ";
var hap = new HtmlDocument();
hap.LoadHtml(html);
string text = HtmlEntity.DeEntitize(hap.DocumentNode.InnerText);
// text is now "LARGELamb "
string[] lines = hap.DocumentNode.SelectNodes("//text()")
.Select(h => HtmlEntity.DeEntitize(h.InnerText)).ToArray();
// lines is { "LARGE", "Lamb", " " }
答案 1 :(得分:1)
如果我们假设您要修复html elements
。
static void Main(string[] args)
{
string html = WebUtility.HtmlDecode("<p>LARGE</p><p>Lamb</p>");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
List<HtmlNode> spanNodes = doc.DocumentNode.Descendants().Where(x => x.Name == "p").ToList();
foreach (HtmlNode node in spanNodes)
{
Console.WriteLine(node.InnerHtml);
}
}
您需要使用HTML Agility Pack。您可以添加这样的参考。:
Install-Package HtmlAgilityPack
答案 2 :(得分:0)
假设:
这是一种快速而肮脏的方式来获得你想要的东西:
static void Main(string[] args)
{
// Split original string on the 'separator' string.
string originalString = "<p>LARGE</p><p>Lamb;<br>;li;ul; ";
string[] sSeparator = new string[] { "</p><p>" };
string[] splitString = originalString.Split(sSeparator, StringSplitOptions.None);
// Prepare to filter the 'prefix' and 'postscript' strings
string prefix = "<p>";
string postfix = ";<br>;li;ul; ";
int prefixLength = prefix.Length;
int postfixLength = postfix.Length;
// Iterate over the split string and clean up
string s = string.Empty;
for (int i = 0; i < splitString.Length; i++)
{
s = splitString[i];
if (s.Contains(prefix))
{
s = s.Remove(s.IndexOf(prefix), prefixLength);
}
if (s.Contains(postfix))
{
s = s.Remove(s.IndexOf(postfix), postfixLength);
}
splitString[i] = s;
Console.WriteLine(splitString[i]);
}
Console.ReadLine();
}
答案 3 :(得分:0)
试试这个
// erase html tags from a string
public static string StripHtml(string target)
{
//Regular expression for html tags
Regex StripHTMLExpression = new Regex("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
return StripHTMLExpression.Replace(target, string.Empty);
}
呼叫
string htmlString="<div><span>hello world!</span></div>";
string strippedString=StripHtml(htmlString);
答案 4 :(得分:0)
DW