C# 如何在C中仅从html中获取父标记文本#

C# 如何在C中仅从html中获取父标记文本#,c#,html,C#,Html,我实际上是在尝试从一个有一些子标记的标记中绘制文本 例如: <p><span>Child Text </span><span class="price">Child Text</span><br /> I need this text</p> 更新:我想我必须使用Htmlagilitypack,所以现在我的问题是如何使用Htmlagilitypack库来实现这一点,我是新手 谢谢如果您可以将“需要此文本”放在一

我实际上是在尝试从一个有一些子标记的标记中绘制文本

例如

<p><span>Child Text </span><span class="price">Child Text</span><br />
I need this text</p>
更新:我想我必须使用Htmlagilitypack,所以现在我的问题是如何使用Htmlagilitypack库来实现这一点,我是新手


谢谢

如果您可以将“需要此文本”放在一个带有id的范围内,那么您只需获取该id的.innerHTML()就可以轻松得多。如果无法更改标记,可以获取menueElement的.innerHTML()和“
”后内容的字符串匹配,但这是非常脆弱的。

从使用正则表达式到web抓取库,有很多方法可以做到这一点。我建议您使用htmlagilitypack,这样您就可以通过xpath准确地满足您的需要。 将引用和名称空间添加到HtmlAgilityPack,我将使用linq(这需要.NET3.5或更高版本),使用下面的代码就可以做到这一点

using HtmlAgilityPack;
using System.Linq;
//这些参考资料必须可用

        private void Form1_Load(object sender, EventArgs e)
        {
            var rawData = "<p><span>Child Text </span><span class=\"price\">Child Text</span><br />I need this text</p>";
            var html = new HtmlAgilityPack.HtmlDocument();
            html.LoadHtml(rawData);
            html.DocumentNode.SelectNodes("//p/text()").ToList().ForEach(x=>MessageBox.Show(x.InnerHtml));
        }
private void Form1\u加载(对象发送方,事件参数e)
{
var rawData=“子文本子文本
我需要此文本”; var html=new HtmlAgilityPack.HtmlDocument(); LoadHtml(rawData); html.DocumentNode.SelectNodes(“//p/text()”).ToList().ForEach(x=>MessageBox.Show(x.InnerHtml)); }
您可以通过将文档文本拆分为不同的部分来获取文本

string text = "<p><span>Child Text </span><span class="price">Child Text</span><br />I need this text</p>";
text = text.Split(new string{"<p><span>Child Text </span><span class="price">Child Text</span><br />"}, StringSplitOptions.None)[1];
// Splits the first part of the text, leaving us with "I need this text</p>"
// We can remove the last </p> many ways, but here I will show you one way.
text = text.Split(new string{"</p>"}, StringSplitOptions.None)[0];
// text now has the value of "I need this text"
string text=“子文本子文本
我需要此文本”; text=text.Split(新字符串{“子文本子文本
“},StringSplitOptions.None)[1]; //拆分文本的第一部分,留下“我需要此文本” //我们可以通过多种方式删除最后的

,但这里我将向您展示一种方法。 text=text.Split(新字符串{“

”},StringSplitOptions.None)[0]; //文本现在具有“我需要此文本”的值

希望这有帮助

因为需要在c#中查找,所以从中删除javascript标记question@CharandeepSingh-你可以对标签进行建议的编辑,你知道吗?基本上你需要直接的子节点,即文本节点。不确定这在
HtmlElement
中是否可行。HTML Agility Pack在这方面可能更灵活。您应该能够迭代菜单元素中包含的元素,并只获取文本节点的内容,但我目前没有启动到windows,因此无法检查。@Oded-我不知道我有这种特权。谢谢;)谢谢robrich,但是我不能对html代码进行更改,而且我有很多标记要通过循环获取,所以匹配字符串不是我的选择。
string text = "<p><span>Child Text </span><span class="price">Child Text</span><br />I need this text</p>";
text = text.Split(new string{"<p><span>Child Text </span><span class="price">Child Text</span><br />"}, StringSplitOptions.None)[1];
// Splits the first part of the text, leaving us with "I need this text</p>"
// We can remove the last </p> many ways, but here I will show you one way.
text = text.Split(new string{"</p>"}, StringSplitOptions.None)[0];
// text now has the value of "I need this text"