コード例 #1
0
        public void NodeFilterUsageTest()
        {
            // Prepare an HTML code
            var code = @"
                <p>Hello</p>
                <img src='image1.png'>
                <img src='image2.png'>
                <p>World!</p>";

            // Initialize a document based on the prepared code
            using (var document = new HTMLDocument(code, "."))
            {
                // To start HTML navigation we need to create an instance of TreeWalker.
                // The specified parameters mean that it starts walking from the root of the document, iterating all nodes and use our custom implementation of the filter
                using (var iterator = document.CreateTreeWalker(document, NodeFilter.SHOW_ALL, new OnlyImageFilter()))
                {
                    while (iterator.NextNode() != null)
                    {
                        // Since we are using our own filter, the current node will always be an instance of the HTMLImageElement.
                        // So, we don't need the additional validations here.
                        var image = (HTMLImageElement)iterator.CurrentNode;

                        Output.WriteLine(image.Src);
                        // output: image1.png
                        // output: image2.png

                        // Set an html variable for the document
                        var html = document.DocumentElement.OuterHTML;

                        Assert.Contains("<p>", html);
                    }
                }
            }
        }