Ho una pagina di test html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Page for test</title>
</head>
<body>
<div class="r_tr">
<span class="r_rs">Inner text<span class="otherSpan" style="display: none">text</span></span>
</div>
</body>
</html>
Voglio ottenere "Testo interno". Sto usando HtmlAgilityPack. Scrivo questo metodo
public string GetInnerTextFromSpan(HtmlDocument doc)
{
const string rowXPath = "//*[@class=\"r_tr\"]";
const string spanXPath = "//*[@class=\"r_rs\"]";
string text = null;
HtmlNodeCollection rows = doc.DocumentNode.SelectNodes(rowXPath);
foreach(HtmlNode row in rows)
{
text = row.SelectSingleNode(spanXPath).InnerText;
Console.WriteLine("textL {0}", text);
}
return text;
}
ma questo metodo restituisce "testo testuale interno". Scrivo alcune unit test per spiegare il mio problema
[Test]
public void TestGetInnerTextFromSpan()
{
var client = new PromtTranslatorClient();
var doc = new HtmlDocument();
doc.Load(@"testPage.html");
var text = client.GetInnerTextFromSpan(doc);
StringAssert.AreEqualIgnoringCase("Inner text", text);
}
e risultato
Expected string length 10 but was 14. Strings differ at index 10.
Expected: "Inner text", ignoring case
But was: "Inner texttext"
---------------------^
Non conosco XPath ma qui è la soluzione che utilizza LINQ:
String inner = (from x in doc.DocumentNode.Descendants()
where x.Name == "span"
&& x.Attributes["class"].Value == "r_rs"
select
(from y in x.ChildNodes
where y.Name == "#text"
select y.InnerText).FirstOrDefault()
).FirstOrDefault();
Innanzitutto, spanXPath
non è corretto. //
all'inizio significa "inizia dalla radice", quindi row.SelectSingleNode(spanXPath)
darà sempre il primo elemento con la classe r_rs
nel documento, non nella riga. Rilasciare //
per risolvere il problema.
Quindi, text()
è l'XPath per un nodo di testo. Puoi usare
var span = row.SelectSingleNode(spanXPath);
var textNode = span.SelectSingleNode("text()");
text = textNode.InnerText;
Console.WriteLine("textL {0}", text);
nel ciclo foreach
per ottenere il primo nodo di testo nello span selezionato.