如何在Windows 8中使用c#解析字符串

本文关键字:字符串 Windows | 更新日期: 2023-09-27 18:17:20

我有一个包含这部分HTML代码的网页:

<meta property="og:type" content="photo" />
    <meta property="og:description" content="descrizione">
    <meta property="og:site_name" content="Site_Name" />
    <meta property="og:title" content="" />
    <meta property="og:image" content="http://addfsfdbyhdfsifd.jpg" />
    <meta property="og:determiner" content="a" />
    <meta property="fb:app_id" content="124024574287414" />
    <meta property="og:url" content="http://addfsfdbyhdfsifd.com" />

如何选择属性="og:image"的内容?我需要得到那个链接来显示在我的应用程序中

如何在Windows 8中使用c#解析字符串

使用HtmlAgilityPack

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var props = doc.DocumentNode.Descendants("meta")
            .ToDictionary( m => m.Attributes["property"].Value,
                            m => m.Attributes["content"].Value);
Console.WriteLine(props["og:image"]);

这是绝对可行的方法。

  1. 我不喜欢用第三方库来解决小问题。顺便说一句,我无意冒犯你的敏捷性。它是超级伟大和强大的。您永远不会想要自己解析HTML。但这是一个很小的边缘情况!为什么要搞砸它?
  2. 你不能确定HTML会被解析,所以你需要别的东西。XML很诱人,但除非您100%肯定这是有效的XHTML(实际上已经没有什么是有效的了),否则最好不要去追求它。只需将其视为字符串解析练习即可。

什么解析字符串最好?正则表达式,就是这样。

这是你的解决方案:

var s = @"
<meta property=""og:type"" content=""photo"" />
<meta property=""og:description"" content=""descrizione"">
<meta property=""og:site_name"" content=""Site_Name"" />
<meta property=""og:title"" content="""" />
<meta property=""og:image"" content=""http://addfsfdbyhdfsifd.jpg"" />
<meta property=""og:determiner"" content=""a"" />
<meta property=""fb:app_id"" content=""124024574287414"" />
<meta property=""og:url"" content=""http://addfsfdbyhdfsifd.com"" />";
// first define what you will look for using regex pattern syntax
var p = @"meta's{1,}property=""og:image""'s{1,}content=""(.+)""'s{0,}/>";
// second let the regex engine use your pattern against your html string
var m = System.Text.RegularExpressions.Regex.Match(s, p);
// third pull out just the part you want from the resulting match
var g = m.Groups[1];
// forth get the value from the meta tag, specifically the og:image you wanted
var i = g.Value;

是的,就是这么简单。而且Regex也使它更加可靠。

祝你好运!

设置HtmlDocument:

代码
var s = @"
<meta property=""og:type"" content=""photo"" />
<meta property=""og:description"" content=""descrizione"">
<meta property=""og:site_name"" content=""Site_Name"" />
<meta property=""og:title"" content="""" />
<meta property=""og:image"" content=""http://addfsfdbyhdfsifd.jpg"" />
<meta property=""og:determiner"" content=""a"" />
<meta property=""fb:app_id"" content=""124024574287414"" />
<meta property=""og:url"" content=""http://addfsfdbyhdfsifd.com"" />";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(s);

查找节点,获取属性。

var node = doc.DocumentNode.SelectNodes("//meta[@property='og:image']").FirstOrDefault();
var content = node != null
    ? node.GetAttributeValue("content", string.Empty)
    : string.Empty;