Lave Loos
Lave Loos

Reputation: 1302

How to unwrap an element if it exists with CsQuery?

I'm using CsQuery to read values of HTML elements.

In advance, I don't know if the <a> element contains a <font> element or not.

Is there a way to read the InnerText of an anchor regardless if it contains a fontelement or not?

Scenario 1: Text inside font element

 <div class="link">
     <a href="http://www.example.com/1">
          <font>Foo</font>
     </a>
</div>

Scenario 2: Text without font element

<div class="link">
     <a href="http://www.example.com/2">
         Foo
     </a>
 </div>

I've got the following working solution:

 var dom = CQ.CreateFromUrl("http://www.myurl.com");
 var a = new CQ(dom.Select("div.link a").InnerHTML);
 var font = a.Select("font");
 var myValue = a.Count() > 0 ? font[0].InnerText : a[0].InnerText;

But it's a bit messy and I'd rather just always remove the font element - if present - so I could go for the anchor value right away. Something like Contents() in combination with UnWrap(), but I haven't succeeded to make it work. Ideas anyone?

Upvotes: 0

Views: 256

Answers (1)

nazarkin659
nazarkin659

Reputation: 503

var dom = CQ.CreateFromUrl("http://www.myurl.com");
string result = dom[".link a"].Text();

Upvotes: 1

Related Questions