我正在尝试解析HTML而我不知道如何使用条件(例如,类名必须是X)。我知道有很多关于敏捷包的话题,但我找不到任何有用的东西。
<div class="main-class">
<a href="LINK">
<img src="IMAGELINK" alt="SOMETEXT" class="image-class">
</a>
</div>
<p> bla bla </p>
<div class="main-class">
<a href="LINK">
<img src="IMAGELINK" alt="SOMETEXT" class="image-class">
</a>
</div>
<div class="main-class">
<a href="LINK">
<img src="IMAGELINK" alt="SOMETEXT" class="image-class">
</a>
<p> asd sadh awww </p>
</div>
我希望得到每个div的href,src和alt,类名为“main-class”, 这是我的代码,但它只打印“p”,因为这只是我知道该怎么做。
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(dataString);
foreach (HtmlNode nodeItem in doc.DocumentNode.Descendants("p").ToArray())
{
Debug.WriteLine(nodeItem.InnerText);
}
我正在使用不支持“SelectNodes”的WP应用
答案 0 :(得分:0)
使用传统的非XPath方式。
注意:检查是否省略了无效值。
string dataString = "<div class=\"main-class\"><a href=\"LINK\"><img src=\"IMAGELINK\" alt=\"SOMETEXT\" class=\"image-class\"></a></div><p> bla bla </p><div class=\"main-class\"><a href=\"LINK\"><img src=\"IMAGELINK\" alt=\"SOMETEXT\" class=\"image-class\"></a></div><div class=\"main-class\"><a href=\"LINK\"><img src=\"IMAGELINK\" alt=\"SOMETEXT\" class=\"image-class\"></a><p> asd sadh awww </p></div>";
var doc = new HtmlDocument();
doc.LoadHtml(dataString);
var elements = doc.DocumentNode.Descendants("div").Where(o => o.GetAttributeValue("class", "") == "main-class");
foreach (var nodeItem in elements)
{
var aTag = nodeItem.Descendants("a").First();
var aTagHrefValue = aTag.Attributes["href"];
var imgTag = nodeItem.Descendants("img").First();
var imgTagSrcValue = imgTag.Attributes["src"];
var imgTagAltValue = imgTag.Attributes["alt"];
Console.WriteLine("a href value: {0}", aTagHrefValue.Value);
Console.WriteLine("img src value: {0}", imgTagSrcValue.Value);
Console.WriteLine("img alt value: {0}", imgTagAltValue.Value);
Console.WriteLine();
}
答案 1 :(得分:0)
foreach (HtmlNode nodeItem in doc.DocumentNode.Descendants("div").Where(p => p.GetAttributeValue("class", "def").Equals("main-class")))
{
foreach (HtmlNode nodeAItem in nodeItem.Descendants("a"))
{
Debug.WriteLine(nodeAItem.GetAttributeValue("href", "def"));
foreach (HtmlNode nodeIMAGEitem in nodeAItem.Descendants("img"))
{
Debug.WriteLine(nodeIMAGEitem.GetAttributeValue("src", "def"));
Debug.WriteLine(nodeIMAGEitem.GetAttributeValue("alt", "def"));
}
}
}
答案 2 :(得分:0)
您可以使用LINQ
var attrs = doc.DocumentNode
.Descendants("div")
.Where(d => d.Attributes != null &&
d.Attributes.Contains("class") &&
d.Attributes["class"].Value.Contains("main-class"))
.Select(d => new
{
anchor = d.SelectSingleNode("a"),
img = d.SelectSingleNode("a") != null
? d.SelectSingleNode("a").SelectSingleNode("img")
: null
})
.Select(d => new
{
href = d.anchor != null
? d.anchor.GetAttributeValue("href", string.Empty)
: string.Empty,
imgsrc = d.img != null
? d.img.GetAttributeValue("src", string.Empty)
: string.Empty,
imgalt = d.img != null
? d.img.GetAttributeValue("alt", string.Empty)
: string.Empty
})
.ToList();