Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 灵活的Html解析_C#_Html_Parsing - Fatal编程技术网

C# 灵活的Html解析

C# 灵活的Html解析,c#,html,parsing,C#,Html,Parsing,有人能帮我解决一下C#中Agility解析Html序列标记的问题吗?我有下面列出的两个问题 在本例中,我希望解析以下Html并将它们存储到结构(列表、堆栈等)中,以便有效地使用这些数据 <h3> header </h3> <p> paragraph 1</p> <p> <a href="www.google.com">Google</a> <a href="www.gizmodo.com">Gizmo

有人能帮我解决一下C#中Agility解析Html序列标记的问题吗?我有下面列出的两个问题

在本例中,我希望解析以下Html并将它们存储到结构(列表、堆栈等)中,以便有效地使用这些数据

<h3> header </h3>
<p> paragraph 1</p>
<p>
<a href="www.google.com">Google</a>
<a href="www.gizmodo.com">Gizmodo</a>
</p>
<ul> 
<li> something is here with a download
<a href="www.google.com">link</a>
</li>
<li> hello 
<img src="www.imagesource.com"/>
</li>
</ul>
  • 解析和存储包含字符串、超链接和图像的混合内容的最佳方法是什么? 这样我以后就可以高效地输出它们了?列表,堆栈? 换句话说,我想存储html中所有可能的内容,并尽可能保留其格式。因此,一旦我将内容重新加载到应用程序上,我就可以以适当的格式将其相似
    谢谢大家!

    如果要提取所有
    href
    src
    属性,可以尝试以下操作:

    using System;
    using System.Linq;
    using HtmlAgilityPack;
    
    public class Program
    {
        static void Main()
        {
            var document = new HtmlDocument();
            document.Load("test.html");
            var links =
                from element in document.DocumentNode.Descendants()
                let href = element.Attributes["href"]
                let src = element.Attributes["src"]
                where href != null || src != null
                select href != null ? href.Value : src.Value;
    
            foreach (var link in links)
            {
                Console.WriteLine(link);
            }
        }
    }
    
    产出:

    www.google.com
    www.gizmodo.com
    www.google.com
    www.imagesource.com
    

    不清楚您希望从这个HTML中提取并存储什么信息。是否要提取超链接的所有
    href
    属性?或者图像的
    href
    src
    ?我想要该html中所有可能的内容,包括h3、all p、li、href和img src。如果可能的话,格式也一样。谢谢。如果内存可用,您可以在HtmlDocument类上使用XmlReader,它将按顺序对每个标记进行顺序读取,但我不确定您期望的输出是否能为您提供可以重建为精确Html的内容。但我还需要提取h3和p的文本!
    www.google.com
    www.gizmodo.com
    www.google.com
    www.imagesource.com