繁体   English   中英

从angleSharp元素获取Xpath

[英]Get Xpath from angleSharp element

有没有确定的方法来检索angleSharp IElement的xPath

我正在尝试将 IElement 传递给 javaScript function,所以我需要一种将angleSharp元素转换为javaScript Dom元素的方法

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

我想调用这个 javaScript function 通过传递来自 C# 代码的元素在页面中,但我从页面中得到一个 angleSharp not found 错误。

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

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);
        }

所以基本上你得到 function 与例如jsService.GetOrCreateJint(document).GetValue("selectLevels"); 并使用其Invoke方法调用它,传入字符串 arguments 用于简单类型和使用JsValue.FromObject转换的IElement例如JsValue.FromObject(jsService.GetOrCreateJint(document), document.QuerySelector("section"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM