Get Xpath from angleSharp element

538 Views Asked by At

Is there any definite way to retrieve the xPath of a angleSharp IElement

I'm trying to pass an IElement to a javaScript function, so I need a way to convert the angleSharp element to a javaScript Dom element

function selectLevels(element, name, level){
    document.querySelectorAll("*").forEach(e => {
        if(e.isEqualNode(element)){
            e.setAttribute('level', level); 
            e.setAttribute('title', name);
        }
    })
}

I want to call this javaScript function which is in the page by passing an element from the C# code bellow, but I get an angleSharp not found error from the page.

IElement element = mainDoc.QuerySelector("strong");
Page.ClientScript.RegisterStartupScript(this.GetType(), "SelectLevel", "selectLevels('" + element + "', '" + name + "', '" + level + "')", true);
1

There are 1 best solutions below

2
On

If you have a HTML document with JavaScript code and want to call a (global) function in the JavaScript code from C# then the following example works for me with AngleSharp 0.15 and AngleSharp.Js 0.14:

        static async Task Main()
        {
            var html = @"<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script>
    function selectLevels(element, name, level){
      element.dataset.level = level;
      element.dataset.title = name;
    }
    </script>
  </head>
  <body>
    <h1>Test</h1>
    <section data-level=1 data-title='section 1'>
      <h2>Section test</h2>
    </section>
  </body>
</html>";

            var jsService = new JsScriptingService();

            var config = Configuration.Default.With(jsService);

            var context = BrowsingContext.New(config);

            var document = await context.OpenAsync(req => req.Content(html));

            var selectLevels = jsService.GetOrCreateJint(document).GetValue("selectLevels");

            var jsElement = JsValue.FromObject(jsService.GetOrCreateJint(document), document.QuerySelector("section"));

            selectLevels.Invoke(jsElement, "2", "section 2");

            Console.WriteLine(document.DocumentElement.OuterHtml);
        }

So basically you get the function with e.g. jsService.GetOrCreateJint(document).GetValue("selectLevels"); and call it with its Invoke method, passing in string arguments for the simple types and the IElement converted with JsValue.FromObject e.g. JsValue.FromObject(jsService.GetOrCreateJint(document), document.QuerySelector("section")).