简体   繁体   English

是否可以在 AngleSharp 中获取元素的行号?

[英]Is it possible to get the Line Number of an Element in AngleSharp?

I am putting together a map of all the inline styles on elements in a large project.我正在将一个大型项目中元素的所有内联样式放在一起。 I would like to show the line number where they are located similar the example below.我想显示它们所在的行号,类似于下面的示例。

Is it possible to get the line number of an element in AngleSharp?是否可以在AngleSharp中获取元素的行号?

        foreach (var file in allFiles)
        {
            string source = File.ReadAllText(file.FullName);

            var parser = new HtmlParser();
            var doc = parser.ParseDocument(source);
            var items = doc.QuerySelectorAll("*[style]");

            sb.AppendLine($"{file.Name} - inline styles({items.Count()})");

            foreach (var item in items)
            {
                sb.AppendLine($"\t\tstyle (**{item.LineNumber}**): {item.GetAttribute("style")}");
            }
        }

Yes this is possible.是的,这是可能的。

Quick example:快速示例:

var parser = new HtmlParser(new HtmlParserOptions
{
    IsKeepingSourceReferences = true,
});
var document = parser.ParseDocument("<html><head></head><body><a href=\"example.com/?h=4&w=8\">&foo</a></body></html>");
document.QuerySelector("body").SourceReference?.Position.Dump();

The output looks as follows:输出如下所示:

在此处输入图片说明

The important part is to use the IsKeepingSourceReferences option, as this will allow you to use SourceReference .重要的部分是使用IsKeepingSourceReferences选项,因为这将允许您使用SourceReference Some (by the parser / spec inserted) elements may not have a source reference, so keep in mind that this may be null .一些(由解析器/规范插入)元素可能没有源引用,所以请记住这可能是null

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

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