diff --git a/html-navigation/add-aria-label-attributes-to-navigation-links-without-descriptive-text-screen-readers.cs b/html-navigation/add-aria-label-attributes-to-navigation-links-without-descriptive-text-screen-readers.cs new file mode 100644 index 0000000..7179825 --- /dev/null +++ b/html-navigation/add-aria-label-attributes-to-navigation-links-without-descriptive-text-screen-readers.cs @@ -0,0 +1,75 @@ +// Add aria‑label attributes to navigation links lacking descriptive text for screen readers. + +using System; +using System.IO; + +class Program +{ + static void Main(string[] args) + { + try + { + string html = "Test"; + string baseUri = "about:blank"; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, baseUri)) + { + // Add aria-label to links without descriptive text + Aspose.Html.Collections.HTMLCollection anchors = document.GetElementsByTagName("a"); + for (int i = 0; i < anchors.Length; i++) + { + Aspose.Html.Dom.Element element = anchors[i] as Aspose.Html.Dom.Element; + if (element != null) + { + Aspose.Html.HTMLAnchorElement anchor = element as Aspose.Html.HTMLAnchorElement; + if (anchor != null) + { + string text = anchor.TextContent != null ? anchor.TextContent.Trim() : string.Empty; + if (string.IsNullOrEmpty(text)) + { + string href = anchor.GetAttribute("href"); + if (!string.IsNullOrEmpty(href)) + { + anchor.SetAttribute("aria-label", href); + } + } + } + } + } + + // Validate accessibility + Aspose.Html.Accessibility.WebAccessibility webAccessibility = new Aspose.Html.Accessibility.WebAccessibility(); + Aspose.Html.Accessibility.AccessibilityValidator validator = webAccessibility.CreateValidator(Aspose.Html.Accessibility.ValidationBuilder.All); + Aspose.Html.Accessibility.Results.ValidationResult validationResult = validator.Validate(document); + if (!validationResult.Success) + { + foreach (Aspose.Html.Accessibility.Results.RuleValidationResult ruleResult in validationResult.Details) + { + if (!ruleResult.Success) + { + foreach (Aspose.Html.Accessibility.ITechniqueResult techResult in ruleResult.Errors) + { + if (techResult.Error.Target.TargetType == Aspose.Html.Accessibility.TargetTypes.HTMLElement) + { + Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)techResult.Error.Target.Item; + string tagName = element.TagName; + string attributeValue = element.GetAttribute("aria-label"); + Console.WriteLine($"Tag: {tagName}, Attribute: {attributeValue}, Message: {techResult.Error.ErrorMessage}"); + } + } + } + } + } + + // Save modified HTML + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.html"); + document.Save(outputPath); + Console.WriteLine($"Modified HTML saved to {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/add_crossorigin_attribute_to_external_script_tags_enable_cors_handling.cs b/html-navigation/add-crossorigin-attribute-external-script-tags-enable-cors-handling.cs similarity index 86% rename from html-navigation/add_crossorigin_attribute_to_external_script_tags_enable_cors_handling.cs rename to html-navigation/add-crossorigin-attribute-external-script-tags-enable-cors-handling.cs index 0e09ed5..2d1660f 100644 --- a/html-navigation/add_crossorigin_attribute_to_external_script_tags_enable_cors_handling.cs +++ b/html-navigation/add-crossorigin-attribute-external-script-tags-enable-cors-handling.cs @@ -1,16 +1,20 @@ // Add a crossorigin attribute to external script tags to enable CORS handling. +using System; + class Program { static void Main() { try { - string htmlContent = ""; + string htmlContent = ""; string tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "sample.html"); System.IO.File.WriteAllText(tempFile, htmlContent); + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); configuration.Security |= Aspose.Html.Sandbox.Scripts; + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(tempFile, configuration)) { Aspose.Html.Collections.HTMLCollection scriptElements = document.GetElementsByTagName("script"); @@ -23,13 +27,14 @@ static void Main() scriptElement.SetAttribute("crossorigin", "anonymous"); } } + string output = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; System.Console.WriteLine(output); } } catch (System.Exception ex) { - System.Console.WriteLine("Error: " + ex.Message); + System.Console.Error.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/html-navigation/add-custom-data-attribute-heading-elements-javascript-interaction.cs b/html-navigation/add-custom-data-attribute-heading-elements-javascript-interaction.cs new file mode 100644 index 0000000..1d35b6c --- /dev/null +++ b/html-navigation/add-custom-data-attribute-heading-elements-javascript-interaction.cs @@ -0,0 +1,32 @@ +// Add a custom data‑attribute to all heading elements for JavaScript interaction later. + +using System; + +class Program +{ + static void Main() + { + try + { + var document = new Aspose.Html.HTMLDocument(); + var body = document.Body; + + var h1 = (Aspose.Html.HTMLHeadingElement)document.CreateElement("h1"); + h1.SetAttribute("data-custom", "heading1"); + h1.AppendChild(document.CreateTextNode("Heading 1")); + body.AppendChild(h1); + + var h2 = (Aspose.Html.HTMLHeadingElement)document.CreateElement("h2"); + h2.SetAttribute("data-custom", "heading2"); + h2.AppendChild(document.CreateTextNode("Heading 2")); + body.AppendChild(h2); + + string outputPath = "output.html"; + document.Save(outputPath); + } + catch (System.Exception ex) + { + System.Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/add-custom-data-tracking-attribute-to-outbound-links-for-analytics.cs b/html-navigation/add-custom-data-tracking-attribute-to-outbound-links-for-analytics.cs new file mode 100644 index 0000000..7872f7c --- /dev/null +++ b/html-navigation/add-custom-data-tracking-attribute-to-outbound-links-for-analytics.cs @@ -0,0 +1,50 @@ +// Add a custom data‑tracking attribute to all outbound links for analytics purposes. + +using System; + +class Program +{ + static void Main(string[] args) + { + try + { + // Sample HTML content + string htmlContent = "" + + "External Link" + + "Local Link" + + ""; + + // Load the document from the HTML string + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + // Select all anchor elements with href attribute + Aspose.Html.Collections.NodeList anchors = document.QuerySelectorAll("a[href]"); + + foreach (Aspose.Html.Dom.Node node in anchors) + { + Aspose.Html.HTMLElement element = node as Aspose.Html.HTMLElement; + if (element != null) + { + string href = element.GetAttribute("href"); + if (!string.IsNullOrEmpty(href) && + (href.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + href.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) + { + // Add custom data-tracking attribute + element.SetAttribute("data-tracking", Guid.NewGuid().ToString()); + } + } + } + + // Save the modified HTML to a file + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine($"Modified HTML saved to: {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/add-language-attribute-html-tag-based-on-detected-content-language.cs b/html-navigation/add-language-attribute-html-tag-based-on-detected-content-language.cs new file mode 100644 index 0000000..1d14dea --- /dev/null +++ b/html-navigation/add-language-attribute-html-tag-based-on-detected-content-language.cs @@ -0,0 +1,28 @@ +// Add a language attribute to the html tag based on detected content language. + +class Program +{ + static void Main() + { + try + { + string htmlContent = "SampleHello world!"; + // Simple language detection based on content + string languageCode = htmlContent.Contains("Bonjour") ? "fr" : "en"; + + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + Aspose.Html.HTMLElement htmlElement = (Aspose.Html.HTMLElement)document.DocumentElement; + htmlElement.SetAttribute("lang", languageCode); + + string outputPath = "output.html"; + document.Save(outputPath); + + System.Console.WriteLine("HTML saved to " + outputPath + " with lang='" + languageCode + "'."); + } + catch (System.Exception ex) + { + System.Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/add_missing_alt_attributes_to_img_tags_using_placeholder_description_for_accessibility.cs b/html-navigation/add-missing-alt-attributes-img-tags-using-placeholder-description-accessibility.cs similarity index 54% rename from html-navigation/add_missing_alt_attributes_to_img_tags_using_placeholder_description_for_accessibility.cs rename to html-navigation/add-missing-alt-attributes-img-tags-using-placeholder-description-accessibility.cs index 88fd1bc..d9fc2a5 100644 --- a/html-navigation/add_missing_alt_attributes_to_img_tags_using_placeholder_description_for_accessibility.cs +++ b/html-navigation/add-missing-alt-attributes-img-tags-using-placeholder-description-accessibility.cs @@ -1,8 +1,6 @@ // Add missing alt attributes to img tags using a placeholder description for accessibility. using System; -using System.IO; -using System.Text; class Program { @@ -10,26 +8,9 @@ static void Main() { try { - // Prepare sample HTML content - string htmlContent = "" + - "" + - "Existing alt" + - ""; - - // Define input and output file paths - string inputPath = "sample.html"; - string outputPath = "output.html"; - - // Write the sample HTML to a file - File.WriteAllText(inputPath, htmlContent, Encoding.UTF8); - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - - // Get all elements + string htmlContent = "Sample

Text

Existing alt"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); Aspose.Html.Collections.HTMLCollection images = document.GetElementsByTagName("img"); - - // Iterate over each image element foreach (Aspose.Html.Dom.Element node in images) { Aspose.Html.HTMLImageElement img = node as Aspose.Html.HTMLImageElement; @@ -43,9 +24,7 @@ static void Main() } } } - - // Save the modified document - document.Save(outputPath); + document.Save("output.html"); } catch (Exception ex) { diff --git a/html-navigation/add-missing-charset-meta-tag-detected-file-encoding-improve-compatibility.cs b/html-navigation/add-missing-charset-meta-tag-detected-file-encoding-improve-compatibility.cs new file mode 100644 index 0000000..973dd92 --- /dev/null +++ b/html-navigation/add-missing-charset-meta-tag-detected-file-encoding-improve-compatibility.cs @@ -0,0 +1,58 @@ +// Add a missing charset meta tag based on detected file encoding to improve compatibility. + +using System; +using System.IO; +using System.Text; + +class Program +{ + static void Main() + { + try + { + // Define input and output paths + string sourcePath = "input.html"; + string outputPath = "output.html"; + + // Create a minimal sample HTML file if it does not exist + if (!File.Exists(sourcePath)) + { + string sampleHtml = "Sample

Hello World

"; + File.WriteAllText(sourcePath, sampleHtml, Encoding.UTF8); + } + + // Detect encoding (for this example we assume UTF-8) + string encodingName = "utf-8"; + string htmlContent = File.ReadAllText(sourcePath, Encoding.GetEncoding(encodingName)); + + // Add charset meta tag if missing + if (!htmlContent.Contains("", StringComparison.OrdinalIgnoreCase)) + { + htmlContent = htmlContent.Replace("", "", StringComparison.OrdinalIgnoreCase); + } + else if (htmlContent.Contains("", StringComparison.OrdinalIgnoreCase)) + { + htmlContent = htmlContent.Replace("", "", StringComparison.OrdinalIgnoreCase); + } + else + { + htmlContent = "" + htmlContent; + } + } + + // Load HTML content into Aspose.HTML document + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Save the modified document + document.Save(outputPath); + + Console.WriteLine($"HTML saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/add_missing_doctype_declaration_at_beginning_of_html_file_to_ensure_standards_mode.cs b/html-navigation/add-missing-doctype-declaration-beginning-html-file-ensure-standards-mode.cs similarity index 57% rename from html-navigation/add_missing_doctype_declaration_at_beginning_of_html_file_to_ensure_standards_mode.cs rename to html-navigation/add-missing-doctype-declaration-beginning-html-file-ensure-standards-mode.cs index 32f60c1..b782791 100644 --- a/html-navigation/add_missing_doctype_declaration_at_beginning_of_html_file_to_ensure_standards_mode.cs +++ b/html-navigation/add-missing-doctype-declaration-beginning-html-file-ensure-standards-mode.cs @@ -2,7 +2,7 @@ using System; using System.IO; -using Aspose.Html; +using System.Text; class Program { @@ -13,18 +13,15 @@ static void Main() string inputPath = "input.html"; string outputPath = "output.html"; - // Create a minimal sample HTML file without DOCTYPE if it doesn't exist + // Create a minimal sample HTML file if it does not exist if (!File.Exists(inputPath)) { string sampleHtml = "Sample

Hello, World!

"; - File.WriteAllText(inputPath, sampleHtml); + File.WriteAllText(inputPath, sampleHtml, Encoding.UTF8); } - // Load the HTML document using Aspose.Html - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - - // Get the outer HTML of the document - string html = document.DocumentElement.OuterHTML; + // Read the HTML content + string html = File.ReadAllText(inputPath, Encoding.UTF8); // Add DOCTYPE if missing if (!html.TrimStart().StartsWith("\n" + html; } - // Save the modified HTML to the output file - File.WriteAllText(outputPath, html); + // Load the HTML into Aspose.HTML document + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank"); - Console.WriteLine("HTML file processed successfully. Output saved to: " + outputPath); + // Save the updated document + document.Save(outputPath); } catch (Exception ex) { - Console.WriteLine("Error: " + ex.Message); + Console.WriteLine(ex.Message); } } } \ No newline at end of file diff --git a/html-navigation/add-nofollow-attribute-external-links-search-engine-crawling.cs b/html-navigation/add-nofollow-attribute-external-links-search-engine-crawling.cs new file mode 100644 index 0000000..bde2a55 --- /dev/null +++ b/html-navigation/add-nofollow-attribute-external-links-search-engine-crawling.cs @@ -0,0 +1,36 @@ +// Add a nofollow attribute to external links to control search engine crawling. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "SampleExternal Local"; + string baseUri = "about:blank"; + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, baseUri)) + { + foreach (Aspose.Html.Dom.Element linkElement in document.Links) + { + string href = linkElement.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + if (href.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + href.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + linkElement.SetAttribute("rel", "nofollow"); + } + } + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine("Processed HTML saved to " + outputPath); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/add_aria_label_attributes_to_navigation_links_lacking_descriptive_text_for_screen_readers.cs b/html-navigation/add_aria_label_attributes_to_navigation_links_lacking_descriptive_text_for_screen_readers.cs deleted file mode 100644 index 05d0c07..0000000 --- a/html-navigation/add_aria_label_attributes_to_navigation_links_lacking_descriptive_text_for_screen_readers.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Add aria‑label attributes to navigation links lacking descriptive text for screen readers. - -using System; -using System.IO; - -class Program -{ - static void Main() - { - try - { - string html = @"Sample"; - - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "")) - { - Aspose.Html.Collections.HTMLCollection links = document.GetElementsByTagName("a"); - for (int i = 0; i < links.Length; i++) - { - Aspose.Html.Dom.Element link = links[i]; - string text = link.TextContent != null ? link.TextContent.Trim() : string.Empty; - if (string.IsNullOrEmpty(text)) - { - string href = link.GetAttribute("href"); - string ariaLabel = !string.IsNullOrEmpty(href) ? $"Link to {href}" : "Navigation link"; - link.SetAttribute("aria-label", ariaLabel); - } - } - - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.html"); - document.Save(outputPath); - Console.WriteLine($"Modified HTML saved to: {outputPath}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/add_custom_data_attribute_to_all_heading_elements_for_javascript_interaction_later.cs b/html-navigation/add_custom_data_attribute_to_all_heading_elements_for_javascript_interaction_later.cs deleted file mode 100644 index e4bab4a..0000000 --- a/html-navigation/add_custom_data_attribute_to_all_heading_elements_for_javascript_interaction_later.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Add a custom data‑attribute to all heading elements for JavaScript interaction later. - -using System; -using Aspose.Html; -using Aspose.Html.Dom; - -class Program -{ - static void Main() - { - try - { - // Create a new HTML document - HTMLDocument doc = new HTMLDocument(); - - // Get the body element - HTMLElement body = doc.Body; - - // Create first heading (h1) with custom data-attribute - HTMLElement h1 = (HTMLElement)doc.CreateElement("h1"); - h1.SetAttribute("data-custom", "heading1"); - h1.AppendChild(doc.CreateTextNode("Sample Heading 1")); - body.AppendChild(h1); - - // Create second heading (h2) with custom data-attribute - HTMLElement h2 = (HTMLElement)doc.CreateElement("h2"); - h2.SetAttribute("data-custom", "heading2"); - h2.AppendChild(doc.CreateTextNode("Sample Heading 2")); - body.AppendChild(h2); - - // Save the document to a file - string outputPath = "output.html"; - doc.Save(outputPath); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/add_language_attribute_to_html_tag_based_on_detected_content_language.cs b/html-navigation/add_language_attribute_to_html_tag_based_on_detected_content_language.cs deleted file mode 100644 index ddd815e..0000000 --- a/html-navigation/add_language_attribute_to_html_tag_based_on_detected_content_language.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Add a language attribute to the html tag based on detected content language. - -using System; - -namespace AsposeHtmlLanguageExample -{ - class Program - { - static void Main() - { - try - { - string htmlContent = "SampleHello world"; - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, ""); - - string language = "en"; - if (htmlContent.Contains("Bonjour")) - { - language = "fr"; - } - else if (htmlContent.Contains("Hola")) - { - language = "es"; - } - - Aspose.Html.Dom.Element htmlElement = document.DocumentElement; - htmlElement.SetAttribute("lang", language); - - string outputPath = "output.html"; - document.Save(outputPath); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - } - } -} \ No newline at end of file diff --git a/html-navigation/add_missing_charset_meta_tag_based_on_detected_file_encoding_to_improve_compatibility.cs b/html-navigation/add_missing_charset_meta_tag_based_on_detected_file_encoding_to_improve_compatibility.cs deleted file mode 100644 index d36b689..0000000 --- a/html-navigation/add_missing_charset_meta_tag_based_on_detected_file_encoding_to_improve_compatibility.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Add a missing charset meta tag based on detected file encoding to improve compatibility. - -using System; -using System.IO; -using System.Text; -using Aspose.Html; -using Aspose.Html.Dom; - -class Program -{ - static void Main() - { - try - { - // Define input and output paths - string sourcePath = "sample.html"; - string outputPath = "output.html"; - - // Create a minimal sample HTML file if it does not exist - if (!File.Exists(sourcePath)) - { - string sampleHtml = "Test

Hello World

"; - File.WriteAllText(sourcePath, sampleHtml, Encoding.UTF8); - } - - // Detect encoding (example: Windows-1252) - string encodingName = "windows-1252"; - Encoding encoding = Encoding.GetEncoding(encodingName); - - // Read HTML content using the detected encoding - string htmlContent = File.ReadAllText(sourcePath, encoding); - - // Load HTML into Aspose.HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, ""); - - // Create element - Aspose.Html.HTMLElement meta = (Aspose.Html.HTMLElement)document.CreateElement("meta"); - meta.SetAttribute("charset", encoding.WebName); - - // Append meta element to - Aspose.Html.HTMLElement head = (Aspose.Html.HTMLElement)document.GetElementsByTagName("head")[0]; - head.AppendChild(meta); - - // Save the modified document - document.Save(outputPath); - - Console.WriteLine($"Document saved to: {outputPath}"); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/add_nofollow_attribute_external_links_control_search_engine_crawling.cs b/html-navigation/add_nofollow_attribute_external_links_control_search_engine_crawling.cs deleted file mode 100644 index 50f1c07..0000000 --- a/html-navigation/add_nofollow_attribute_external_links_control_search_engine_crawling.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Add a nofollow attribute to external links to control search engine crawling. - -namespace Example -{ - class Program - { - static void Main(string[] args) - { - try - { - string inputPath = "sample.html"; - string outputPath = "output.html"; - - if (!System.IO.File.Exists(inputPath)) - { - string sampleHtml = "TestExternal Link Local Link"; - System.IO.File.WriteAllText(inputPath, sampleHtml); - } - - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath)) - { - Aspose.Html.Collections.HTMLCollection links = document.GetElementsByTagName("a"); - for (int i = 0; i < links.Length; i++) - { - Aspose.Html.Dom.Element link = (Aspose.Html.Dom.Element)links[i]; - string href = link.GetAttribute("href"); - if (!string.IsNullOrEmpty(href) && (href.StartsWith("http://") || href.StartsWith("https://"))) - { - link.SetAttribute("rel", "nofollow"); - } - } - - document.Save(outputPath); - System.Console.WriteLine($"Processed document saved to {outputPath}"); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine($"Error: {ex.Message}"); - } - } - } -} \ No newline at end of file diff --git a/html-navigation/append-new-stylesheet-link-element-to-head-reference-external-css-file.cs b/html-navigation/append-new-stylesheet-link-element-to-head-reference-external-css-file.cs new file mode 100644 index 0000000..f92f363 --- /dev/null +++ b/html-navigation/append-new-stylesheet-link-element-to-head-reference-external-css-file.cs @@ -0,0 +1,37 @@ +// Append a new stylesheet link element to the head to reference an external CSS file. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "

Hello World

"; + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + var head = document.QuerySelector("head") as Aspose.Html.HTMLElement; + if (head == null) + { + head = (Aspose.Html.HTMLElement)document.CreateElement("head"); + var htmlElement = document.DocumentElement; + var body = document.Body; + htmlElement.InsertBefore(head, body); + } + + var link = (Aspose.Html.HTMLElement)document.CreateElement("link"); + link.SetAttribute("rel", "stylesheet"); + link.SetAttribute("href", "styles.css"); + head.AppendChild(link); + + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine("Document saved to " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/append_new_stylesheet_link_element_to_head_reference_external_css_file.cs b/html-navigation/append_new_stylesheet_link_element_to_head_reference_external_css_file.cs deleted file mode 100644 index c3ce6ff..0000000 --- a/html-navigation/append_new_stylesheet_link_element_to_head_reference_external_css_file.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Append a new stylesheet link element to the head to reference an external CSS file. - -using System; -using System.IO; -using System.Linq; -using Aspose.Html; - -class Program -{ - static void Main() - { - try - { - string inputPath = "sample.html"; - string outputPath = "output.html"; - - // Create a minimal HTML file - string htmlContent = ""; - File.WriteAllText(inputPath, htmlContent); - - // Load the document - HTMLDocument document = new HTMLDocument(inputPath); - - // Get or create the element - HTMLElement head = Enumerable.First(document.GetElementsByTagName("head")) as HTMLElement; - if (head == null) - { - head = (HTMLElement)document.CreateElement("head"); - document.DocumentElement.InsertBefore(head, document.Body); - } - - // Create the element for external CSS - HTMLElement link = (HTMLElement)document.CreateElement("link"); - link.SetAttribute("rel", "stylesheet"); - link.SetAttribute("href", "styles.css"); - - // Append the link to the head - head.AppendChild(link); - - // Save the modified document - document.Save(outputPath); - - Console.WriteLine("External stylesheet link added. Document saved to: " + outputPath); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/batch_process_html_folder_extract_headings_hierarchy_save_json_outline.cs b/html-navigation/batch-process-folder-html-files-extracting-headings-hierarchy-saving-each-json-outline.cs similarity index 66% rename from html-navigation/batch_process_html_folder_extract_headings_hierarchy_save_json_outline.cs rename to html-navigation/batch-process-folder-html-files-extracting-headings-hierarchy-saving-each-json-outline.cs index 5350ef9..d7bc0e5 100644 --- a/html-navigation/batch_process_html_folder_extract_headings_hierarchy_save_json_outline.cs +++ b/html-navigation/batch-process-folder-html-files-extracting-headings-hierarchy-saving-each-json-outline.cs @@ -1,9 +1,10 @@ // Batch process a folder of HTML files, extracting headings hierarchy and saving each as a JSON outline. using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Text.Json; +using Aspose.Html; class OutlineNode { @@ -18,8 +19,8 @@ static void Main() { try { - string inputFolder = "InputHtml"; - string outputFolder = "OutputJson"; + string inputFolder = "HTMLFiles"; + string outputFolder = "JsonOut"; if (!Directory.Exists(inputFolder)) Directory.CreateDirectory(inputFolder); @@ -27,29 +28,38 @@ static void Main() Directory.CreateDirectory(outputFolder); // Create a sample HTML file if none exist - if (Directory.GetFiles(inputFolder, "*.html").Length == 0) + string[] existingFiles = Directory.GetFiles(inputFolder, "*.html"); + if (existingFiles.Length == 0) { string samplePath = Path.Combine(inputFolder, "sample.html"); - File.WriteAllText(samplePath, "

Title

Section

Subsection

"); + File.WriteAllText(samplePath, + "" + + "

Main Title

" + + "

Section 1

" + + "

Subsection 1.1

" + + "

Section 2

" + + ""); } foreach (string htmlPath in Directory.GetFiles(inputFolder, "*.html")) { - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); + HTMLDocument document = new HTMLDocument(htmlPath); var headings = document.QuerySelectorAll("h1, h2, h3, h4, h5, h6"); var root = new List(); var stack = new Stack(); for (int i = 0; i < headings.Length; i++) { - Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)headings[i]; + HTMLElement element = (HTMLElement)headings[i]; string tag = element.TagName.ToLower(); int level = int.Parse(tag.Substring(1)); - OutlineNode node = new OutlineNode(); - node.Text = element.TextContent.Trim(); - node.Level = level; - node.Children = new List(); + OutlineNode node = new OutlineNode + { + Text = element.TextContent.Trim(), + Level = level, + Children = new List() + }; while (stack.Count > 0 && stack.Peek().Level >= level) stack.Pop(); @@ -66,12 +76,10 @@ static void Main() string jsonPath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(htmlPath) + ".json"); File.WriteAllText(jsonPath, json); } - - Console.WriteLine("Processing completed successfully."); } catch (Exception ex) { - Console.WriteLine($"Error: {ex.Message}"); + Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/html-navigation/clone-navigation-menu-element-insert-clone-at-end-of-body.cs b/html-navigation/clone-navigation-menu-element-insert-clone-at-end-of-body.cs new file mode 100644 index 0000000..19dcd66 --- /dev/null +++ b/html-navigation/clone-navigation-menu-element-insert-clone-at-end-of-body.cs @@ -0,0 +1,30 @@ +// Clone a navigation menu element and insert the clone at the end of the body. + +using System; + +class Program +{ + static void Main() + { + try + { + string html = "Sample"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank"); + + Aspose.Html.HTMLElement nav = (Aspose.Html.HTMLElement)System.Linq.Enumerable.First(document.GetElementsByTagName("nav")); + Aspose.Html.HTMLElement clone = (Aspose.Html.HTMLElement)document.CreateElement("nav"); + clone.InnerHTML = nav.InnerHTML; + clone.SetAttribute("id", "mainClone"); + + Aspose.Html.HTMLElement body = (Aspose.Html.HTMLElement)System.Linq.Enumerable.First(document.GetElementsByTagName("body")); + body.AppendChild(clone); + + Aspose.Html.Saving.HTMLSaveOptions options = new Aspose.Html.Saving.HTMLSaveOptions(); + document.Save("output.html", options); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/clone_navigation_menu_element_and_insert_clone_at_end_of_body.cs b/html-navigation/clone_navigation_menu_element_and_insert_clone_at_end_of_body.cs deleted file mode 100644 index 31e1a8f..0000000 --- a/html-navigation/clone_navigation_menu_element_and_insert_clone_at_end_of_body.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Clone a navigation menu element and insert the clone at the end of the body. - -using System; -using System.Linq; - -class Program -{ - static void Main() - { - try - { - // Sample HTML containing a navigation menu - string html = "Sample"; - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html); - - // Find the navigation element - Aspose.Html.HTMLElement nav = document.QuerySelector("nav") as Aspose.Html.HTMLElement; - if (nav == null) - { - Console.WriteLine("Navigation element not found."); - return; - } - - // Clone the navigation element (deep clone) - Aspose.Html.Dom.Element clonedNav = nav.CloneNode(true) as Aspose.Html.Dom.Element; - - // Get the body element - Aspose.Html.HTMLElement body = (Aspose.Html.HTMLElement)document.GetElementsByTagName("body").First(); - - // Insert the cloned navigation at the end of the body - body.AppendChild(clonedNav); - - // Save the modified document - Aspose.Html.Saving.HTMLSaveOptions options = new Aspose.Html.Saving.HTMLSaveOptions(); - string outputPath = "output.html"; - document.Save(outputPath, options); - - Console.WriteLine($"Document saved to {outputPath}"); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/compare-two-html-documents-diff-report-added-removed-nodes.cs b/html-navigation/compare-two-html-documents-diff-report-added-removed-nodes.cs new file mode 100644 index 0000000..a172a4d --- /dev/null +++ b/html-navigation/compare-two-html-documents-diff-report-added-removed-nodes.cs @@ -0,0 +1,120 @@ +// Compare two HTML documents and generate a diff report highlighting added and removed nodes. + +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Define file paths + string inputPath1 = "doc1.html"; + string inputPath2 = "doc2.html"; + string outputPath = "diff_report.txt"; + + // Create sample HTML files if they do not exist + if (!File.Exists(inputPath1)) + { + File.WriteAllText(inputPath1, +@" +Document 1 + +

Paragraph A

+
Div 1
+ +"); + } + + if (!File.Exists(inputPath2)) + { + File.WriteAllText(inputPath2, +@" +Document 2 + +

Paragraph A

+

Paragraph B

+
Div 1
+New Span + +"); + } + + // Load documents + HTMLDocument document1 = new HTMLDocument(inputPath1); + HTMLDocument document2 = new HTMLDocument(inputPath2); + + // Collect outer HTML of all elements in each document + HashSet set1 = new HashSet(); + HashSet set2 = new HashSet(); + + Aspose.Html.Collections.NodeList nodes1 = document1.QuerySelectorAll("*"); + foreach (Node node in nodes1) + { + HTMLElement element = node as HTMLElement; + if (element != null) + { + set1.Add(element.OuterHTML); + } + } + + Aspose.Html.Collections.NodeList nodes2 = document2.QuerySelectorAll("*"); + foreach (Node node in nodes2) + { + HTMLElement element = node as HTMLElement; + if (element != null) + { + set2.Add(element.OuterHTML); + } + } + + // Determine added and removed nodes + List added = new List(); + foreach (string html in set2) + { + if (!set1.Contains(html)) + { + added.Add(html); + } + } + + List removed = new List(); + foreach (string html in set1) + { + if (!set2.Contains(html)) + { + removed.Add(html); + } + } + + // Write diff report + using (StreamWriter writer = new StreamWriter(outputPath)) + { + writer.WriteLine("=== Added Nodes ==="); + foreach (string html in added) + { + writer.WriteLine(html); + } + + writer.WriteLine(); + writer.WriteLine("=== Removed Nodes ==="); + foreach (string html in removed) + { + writer.WriteLine(html); + } + } + + Console.WriteLine("Diff report generated at: " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/configure-parser-ignore-xml-namespaces-when-navigating-html-documents-containing-mixed-content.cs b/html-navigation/configure-parser-ignore-xml-namespaces-when-navigating-html-documents-containing-mixed-content.cs new file mode 100644 index 0000000..7392106 --- /dev/null +++ b/html-navigation/configure-parser-ignore-xml-namespaces-when-navigating-html-documents-containing-mixed-content.cs @@ -0,0 +1,28 @@ +// Configure the parser to ignore XML namespaces when navigating HTML documents containing mixed content. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = ""; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("rect"); + for (int i = 0; i < elements.Length; i++) + { + Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)elements[i]; + System.Console.WriteLine(element.TagName); + } + } + } + catch (Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/configure_parser_treat_unknown_tags_as_generic_elements_instead_of_throwing_errors.cs b/html-navigation/configure-parser-treat-unknown-tags-as-generic-elements-instead-of-throwing-errors.cs similarity index 61% rename from html-navigation/configure_parser_treat_unknown_tags_as_generic_elements_instead_of_throwing_errors.cs rename to html-navigation/configure-parser-treat-unknown-tags-as-generic-elements-instead-of-throwing-errors.cs index 43b0e21..df92af8 100644 --- a/html-navigation/configure_parser_treat_unknown_tags_as_generic_elements_instead_of_throwing_errors.cs +++ b/html-navigation/configure-parser-treat-unknown-tags-as-generic-elements-instead-of-throwing-errors.cs @@ -1,7 +1,6 @@ // Configure the parser to treat unknown tags as generic elements instead of throwing errors. using System; -using System.IO; class Program { @@ -9,17 +8,8 @@ static void Main() { try { - // Sample HTML with an unknown tag string htmlContent = "Test"; - - // Write HTML to a temporary file - string tempFile = Path.Combine(Path.GetTempPath(), "sample.html"); - File.WriteAllText(tempFile, htmlContent); - - // Load the document from the temporary file - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(new Aspose.Html.Url(tempFile)); - - // Retrieve and print unknown tag elements + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("custom-tag"); for (int i = 0; i < elements.Length; i++) { @@ -29,7 +19,7 @@ static void Main() } catch (Exception ex) { - System.Console.WriteLine("Error: " + ex.Message); + System.Console.Error.WriteLine($"Error: {ex.Message}"); } } } \ No newline at end of file diff --git a/html-navigation/convert-all-i-tags-to-em-tags-for-better-accessibility-compliance-throughout-document.cs b/html-navigation/convert-all-i-tags-to-em-tags-for-better-accessibility-compliance-throughout-document.cs new file mode 100644 index 0000000..a3253d4 --- /dev/null +++ b/html-navigation/convert-all-i-tags-to-em-tags-for-better-accessibility-compliance-throughout-document.cs @@ -0,0 +1,43 @@ +// Convert all tags to tags for better accessibility compliance throughout the document. + +using System; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content + string htmlContent = "

This is italic and another example.

"; + + // Load HTML document from inline content + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Find all elements + Aspose.Html.Collections.NodeList iElements = document.QuerySelectorAll("i"); + + // Replace each with + for (int index = 0; index < iElements.Length; index++) + { + Aspose.Html.Dom.Node node = iElements[index]; + Aspose.Html.HTMLElement iElement = node as Aspose.Html.HTMLElement; + if (iElement != null) + { + Aspose.Html.HTMLElement emElement = (Aspose.Html.HTMLElement)document.CreateElement("em"); + emElement.InnerHTML = iElement.InnerHTML; + iElement.ParentNode.ReplaceChild(emElement, iElement); + } + } + + // Save the modified document + string outputPath = "output.html"; + document.Save(outputPath); + System.Console.WriteLine($"Modified HTML saved to: {outputPath}"); + } + catch (Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert-all-relative-image-source-urls-to-absolute-urls-based-on-document-base-tag.cs b/html-navigation/convert-all-relative-image-source-urls-to-absolute-urls-based-on-document-base-tag.cs new file mode 100644 index 0000000..7e26964 --- /dev/null +++ b/html-navigation/convert-all-relative-image-source-urls-to-absolute-urls-based-on-document-base-tag.cs @@ -0,0 +1,60 @@ +// Convert all relative image source URLs to absolute URLs based on the document’s base tag. + +using System; + +class Program +{ + static void Main() + { + try + { + // Sample HTML with a base tag and relative image sources + string htmlContent = @" + + + + + +

Sample Page

+ Picture 1 + External Image + Embedded Image + +"; + + // Load the document (inline content) with a placeholder base URI + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all elements + Aspose.Html.Collections.HTMLCollection images = document.GetElementsByTagName("img"); + + // Iterate through the collection + foreach (Aspose.Html.Dom.Element imageElement in images) + { + string src = imageElement.GetAttribute("src"); + if (string.IsNullOrEmpty(src)) + continue; + + // Skip already absolute URLs and data URIs + if (src.StartsWith("http", StringComparison.OrdinalIgnoreCase) || + src.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + // Resolve relative URL against the document's base URI + Aspose.Html.Url resolvedUrl = new Aspose.Html.Url(src, document.BaseURI); + imageElement.SetAttribute("src", resolvedUrl.ToString()); + } + + // Save the modified document + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine("Document saved to: " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert_html_document_to_plain_text_preserving_line_breaks_readability.cs b/html-navigation/convert-html-document-to-plain-text-preserving-line-breaks-readability.cs similarity index 77% rename from html-navigation/convert_html_document_to_plain_text_preserving_line_breaks_readability.cs rename to html-navigation/convert-html-document-to-plain-text-preserving-line-breaks-readability.cs index 8599931..c3c9b99 100644 --- a/html-navigation/convert_html_document_to_plain_text_preserving_line_breaks_readability.cs +++ b/html-navigation/convert-html-document-to-plain-text-preserving-line-breaks-readability.cs @@ -2,8 +2,8 @@ using System; using System.IO; -using Aspose.Html.Saving; using Aspose.Html.Converters; +using Aspose.Html.Saving; class Program { @@ -11,9 +11,11 @@ static void Main() { try { - string htmlContent = "

Hello

World

"; - string baseUri = ""; + string htmlContent = "

Title

First line.
Second line.

"; + string baseUri = "about:blank"; + MarkdownSaveOptions options = new MarkdownSaveOptions(); + string tempPath = Path.GetTempFileName(); Aspose.Html.Converters.Converter.ConvertHTML(htmlContent, baseUri, options, tempPath); @@ -21,7 +23,7 @@ static void Main() string plainText = File.ReadAllText(tempPath); File.Delete(tempPath); - Console.WriteLine("Plain text output:"); + Console.WriteLine("Converted plain text:"); Console.WriteLine(plainText); } catch (Exception ex) diff --git a/html-navigation/convert-html-email-templates-to-plain-text-preserving-line-breaks-and-links.cs b/html-navigation/convert-html-email-templates-to-plain-text-preserving-line-breaks-and-links.cs new file mode 100644 index 0000000..0edde56 --- /dev/null +++ b/html-navigation/convert-html-email-templates-to-plain-text-preserving-line-breaks-and-links.cs @@ -0,0 +1,35 @@ +// Convert HTML email templates to plain text while preserving line breaks and links. + +using System; +using Aspose.Html.Converters; +using Aspose.Html.Saving; + +class Program +{ + static void Main() + { + try + { + string htmlContent = @" + +

Welcome to Our Newsletter

+

Hello John,

+

We are excited to share the latest updates with you.

+

Visit our website for more details.

+

Best regards,
The Team

+ +"; + string baseUri = "about:blank"; + string outputPath = "email_plain_text.txt"; + + TextSaveOptions options = new TextSaveOptions(); + Aspose.Html.Converters.Converter.ConvertHTML(htmlContent, baseUri, options, outputPath); + + Console.WriteLine($"Plain text email saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert-html-table-to-json-array-preserving-column-headers-object-keys.cs b/html-navigation/convert-html-table-to-json-array-preserving-column-headers-object-keys.cs new file mode 100644 index 0000000..2b6b553 --- /dev/null +++ b/html-navigation/convert-html-table-to-json-array-preserving-column-headers-object-keys.cs @@ -0,0 +1,60 @@ +// Convert an HTML table into a JSON array preserving column headers as object keys. + +public class Program +{ + public static void Main() + { + try + { + string htmlContent = "
NameAge
Alice30
Bob25
"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + Aspose.Html.Collections.HTMLCollection tables = document.GetElementsByTagName("table"); + var jsonArray = new System.Collections.Generic.List>(); + foreach (var tableNode in tables) + { + if (tableNode is Aspose.Html.HTMLTableElement table) + { + Aspose.Html.Collections.HTMLCollection rows = table.GetElementsByTagName("tr"); + System.Collections.Generic.List headers = null; + foreach (var rowNode in rows) + { + if (rowNode is Aspose.Html.HTMLTableRowElement row) + { + Aspose.Html.Collections.HTMLCollection cells = row.Cells; + if (headers == null) + { + headers = new System.Collections.Generic.List(); + foreach (var cell in cells) + { + string headerText = cell.TextContent?.Trim() ?? ""; + headers.Add(headerText); + } + } + else + { + var dict = new System.Collections.Generic.Dictionary(); + int index = 0; + foreach (var cell in cells) + { + string cellText = cell.TextContent?.Trim() ?? ""; + string key = index < headers.Count ? headers[index] : $"Column{index}"; + dict[key] = cellText; + index++; + } + jsonArray.Add(dict); + } + } + } + } + } + string json = System.Text.Json.JsonSerializer.Serialize(jsonArray, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }); + string outputPath = "output.json"; + System.IO.File.WriteAllText(outputPath, json); + System.Console.WriteLine($"JSON saved to {outputPath}"); + } + catch (System.Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert-inline-svg-elements-to-external-files-and-replace-with-img-references.cs b/html-navigation/convert-inline-svg-elements-to-external-files-and-replace-with-img-references.cs new file mode 100644 index 0000000..f8cec6d --- /dev/null +++ b/html-navigation/convert-inline-svg-elements-to-external-files-and-replace-with-img-references.cs @@ -0,0 +1,52 @@ +// Convert inline SVG elements to external files and replace them with references. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; +using Aspose.Html; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +class Program +{ + static void Main() + { + try + { + string htmlPath = "sample.html"; + string outputPath = "output.html"; + + if (!File.Exists(htmlPath)) + { + string sampleHtml = "

Test

"; + File.WriteAllText(htmlPath, sampleHtml); + } + + HTMLDocument document = new HTMLDocument(htmlPath); + Aspose.Html.Collections.NodeList svgElements = document.QuerySelectorAll("svg"); + + for (int i = 0; i < svgElements.Length; i++) + { + HTMLElement svgElement = (HTMLElement)svgElements[i]; + string svgMarkup = svgElement.OuterHTML; + string imagePath = $"image{i}.png"; + + ImageSaveOptions options = new ImageSaveOptions(); + Aspose.Html.Converters.Converter.ConvertSVG(svgMarkup, "about:blank", options, imagePath); + + Element imgElement = document.CreateElement("img"); + imgElement.SetAttribute("src", imagePath); + + svgElement.ParentNode.ReplaceChild(imgElement, svgElement); + } + + document.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert-relative-urls-in-anchor-tags-to-absolute-urls-using-document-base-url.cs b/html-navigation/convert-relative-urls-in-anchor-tags-to-absolute-urls-using-document-base-url.cs new file mode 100644 index 0000000..599df72 --- /dev/null +++ b/html-navigation/convert-relative-urls-in-anchor-tags-to-absolute-urls-using-document-base-url.cs @@ -0,0 +1,32 @@ +// Convert relative URLs in anchor tags to absolute URLs using the document’s base URL. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "LinkRoot"; + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + foreach (Aspose.Html.Dom.Element linkElement in document.Links) + { + string href = linkElement.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + + var absoluteUrl = new Aspose.Html.Url(href, document.BaseURI); + linkElement.SetAttribute("href", absoluteUrl.ToString()); + } + + string resultHtml = document.DocumentElement.OuterHTML; + Console.WriteLine(resultHtml); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert-uppercase-tag-names-to-lowercase-to-ensure-html5-compliance-throughout-document.cs b/html-navigation/convert-uppercase-tag-names-to-lowercase-to-ensure-html5-compliance-throughout-document.cs new file mode 100644 index 0000000..3277b22 --- /dev/null +++ b/html-navigation/convert-uppercase-tag-names-to-lowercase-to-ensure-html5-compliance-throughout-document.cs @@ -0,0 +1,32 @@ +// Convert all uppercase tag names to lowercase to ensure HTML5 compliance throughout the document. + +using System; +using System.Text.RegularExpressions; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "
Test
"; + // Load HTML content using Aspose.Html + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Convert uppercase tag names to lowercase + string lowerHtml = Regex.Replace(htmlContent, @"<(/?)([A-Z]+)(\s|>)", m => + $"<{m.Groups[1].Value}{m.Groups[2].Value.ToLower()}{m.Groups[3].Value}"); + + Console.WriteLine("Original HTML:"); + Console.WriteLine(htmlContent); + Console.WriteLine(); + Console.WriteLine("HTML with lowercase tags:"); + Console.WriteLine(lowerHtml); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/convert_html_email_templates_plain_text_preserving_line_breaks_and_links.cs b/html-navigation/convert_html_email_templates_plain_text_preserving_line_breaks_and_links.cs deleted file mode 100644 index 7cc6498..0000000 --- a/html-navigation/convert_html_email_templates_plain_text_preserving_line_breaks_and_links.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Convert HTML email templates to plain text while preserving line breaks and links. - -public class Program -{ - public static void Main() - { - try - { - string htmlContent = "

Hello World

This is a sample email.
Visit our site for more info.

"; - string baseUri = ""; - string outputPath = "email.txt"; - - Aspose.Html.Saving.TextSaveOptions options = new Aspose.Html.Saving.TextSaveOptions(); - - Aspose.Html.Converters.Converter.ConvertHTML(htmlContent, baseUri, options, outputPath); - - System.Console.WriteLine("Conversion completed. Output saved to " + outputPath); - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/convert_html_table_to_json_array_preserving_column_headers_object_keys.cs b/html-navigation/convert_html_table_to_json_array_preserving_column_headers_object_keys.cs deleted file mode 100644 index 5e131cd..0000000 --- a/html-navigation/convert_html_table_to_json_array_preserving_column_headers_object_keys.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Convert an HTML table into a JSON array preserving column headers as object keys. - -using System; -using System.IO; -using System.Text; -using System.Collections.Generic; -using System.Text.Json; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; - -class Program -{ - static void Main() - { - try - { - // Prepare sample HTML with a table - string htmlPath = "sample.html"; - string htmlContent = "Sample" + - "" + - "" + - "" + - "" + - "
NameAgeCity
Alice30New York
Bob25London
" + - ""; - File.WriteAllText(htmlPath, htmlContent, Encoding.UTF8); - - // Load the HTML document - HTMLDocument document = new HTMLDocument(htmlPath); - - // Get all tables - HTMLCollection tables = document.GetElementsByTagName("table"); - var jsonArray = new List>(); - - foreach (var tableNode in tables) - { - if (tableNode is HTMLTableElement table) - { - // Get all rows - HTMLCollection rows = table.GetElementsByTagName("tr"); - List headers = null; - - foreach (var rowNode in rows) - { - if (rowNode is HTMLTableRowElement row) - { - HTMLCollection cells = row.Cells; - List cellTexts = new List(); - foreach (var cell in cells) - { - string cellText = cell.TextContent?.Trim(); - cellTexts.Add(cellText); - } - - // First row assumed as header - if (headers == null) - { - headers = cellTexts; - } - else - { - var obj = new Dictionary(); - for (int i = 0; i < headers.Count && i < cellTexts.Count; i++) - { - obj[headers[i]] = cellTexts[i]; - } - jsonArray.Add(obj); - } - } - } - } - } - - // Serialize to JSON - string jsonOutput = JsonSerializer.Serialize(jsonArray, new JsonSerializerOptions { WriteIndented = true }); - string jsonPath = "output.json"; - File.WriteAllText(jsonPath, jsonOutput, Encoding.UTF8); - - Console.WriteLine("JSON conversion completed. Output written to " + jsonPath); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/convert_relative_urls_anchor_tags_to_absolute_using_document_base_url.cs b/html-navigation/convert_relative_urls_anchor_tags_to_absolute_using_document_base_url.cs deleted file mode 100644 index bb2e883..0000000 --- a/html-navigation/convert_relative_urls_anchor_tags_to_absolute_using_document_base_url.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Convert relative URLs in anchor tags to absolute URLs using the document’s base URL. - -using System; -using System.IO; -using Aspose.Html; -using Aspose.Html.Dom; -using Aspose.Html.Net; - -class Program -{ - static void Main() - { - try - { - // Create a sample HTML file with relative links - string htmlContent = "LinkAbsLink"; - string inputPath = "sample.html"; - File.WriteAllText(inputPath, htmlContent); - - // Load the HTML document - HTMLDocument document = new HTMLDocument(inputPath); - - // Convert relative hrefs to absolute URLs - foreach (Element linkElement in document.Links) - { - string href = linkElement.GetAttribute("href"); - if (string.IsNullOrEmpty(href)) - continue; - - Url resolvedUrl = new Url(href, document.BaseURI); - linkElement.SetAttribute("href", resolvedUrl.ToString()); - } - - // Output the resulting HTML - string resultHtml = document.DocumentElement.OuterHTML; - Console.WriteLine(resultHtml); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/convert_uppercase_tag_names_to_lowercase_for_html5_compliance_throughout_document.cs b/html-navigation/convert_uppercase_tag_names_to_lowercase_for_html5_compliance_throughout_document.cs deleted file mode 100644 index d3ec500..0000000 --- a/html-navigation/convert_uppercase_tag_names_to_lowercase_for_html5_compliance_throughout_document.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Convert all uppercase tag names to lowercase to ensure HTML5 compliance throughout the document. - -using System; -using System.IO; -using System.Text.RegularExpressions; - -class Program -{ - static void Main() - { - try - { - // Sample HTML with uppercase tag names - string htmlContent = "Sample
Content
"; - - // Load HTML into Aspose.Html.HTMLDocument - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, ""); - - // Get the outer HTML of the document - string originalHtml = ((Aspose.Html.HTMLElement)document.DocumentElement).OuterHTML; - - // Convert uppercase tag names to lowercase using regex - string lowerCaseHtml = Regex.Replace(originalHtml, @"<\s*/?\s*([A-Z][A-Z0-9]*)", m => - { - string tag = m.Groups[1].Value; - return m.Value.Replace(tag, tag.ToLowerInvariant()); - }); - - // Define output path - string outputPath = "output.html"; - - // Save the transformed HTML to a file - File.WriteAllText(outputPath, lowerCaseHtml); - - Console.WriteLine("HTML tags converted to lowercase and saved to: " + outputPath); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/detect-and-log-parsing-warnings-unknown-tags-attributes-during-load.cs b/html-navigation/detect-and-log-parsing-warnings-unknown-tags-attributes-during-load.cs new file mode 100644 index 0000000..ca2c9fb --- /dev/null +++ b/html-navigation/detect-and-log-parsing-warnings-unknown-tags-attributes-during-load.cs @@ -0,0 +1,49 @@ +// Detect and log any parsing warnings such as unknown tags or attributes during load. + +using System; +using System.Net; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "TestHello"; + + // Create configuration and add a custom message handler to capture warnings + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + Aspose.Html.Net.MessageHandlerCollection handlers = networkService.MessageHandlers; + handlers.Insert(0, new LogMessageHandler()); + + // Load the HTML document using the configuration + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank", configuration); + + // Example processing: list all element tag names + Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("*"); + for (int i = 0; i < elements.Length; i++) + { + Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)elements[i]; + Console.WriteLine(element.TagName); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} + +// Custom message handler that logs non‑OK HTTP responses as warnings +class LogMessageHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + if (context.Response.StatusCode != HttpStatusCode.OK) + { + Console.WriteLine($"Warning: Request to {context.Request.RequestUri} returned status {context.Response.StatusCode}"); + } + Next(context); + } +} \ No newline at end of file diff --git a/html-navigation/detect-and-remove-empty-elements-without-child-nodes-or-text-content.cs b/html-navigation/detect-and-remove-empty-elements-without-child-nodes-or-text-content.cs new file mode 100644 index 0000000..ae00aff --- /dev/null +++ b/html-navigation/detect-and-remove-empty-elements-without-child-nodes-or-text-content.cs @@ -0,0 +1,55 @@ +// Detect and remove empty elements that contain no child nodes or text content. + +using System; + +class Program +{ + static void Main() + { + try + { + string inputPath = "sample.html"; + string outputPath = "output.html"; + + if (!System.IO.File.Exists(inputPath)) + { + System.IO.File.WriteAllText(inputPath, "

Text

"); + } + + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); + + RemoveEmptyElements(document.DocumentElement); + + document.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + static void RemoveEmptyElements(Aspose.Html.Dom.Node node) + { + var child = node.FirstChild; + while (child != null) + { + var next = child.NextSibling; + + // Recursively process child nodes first + RemoveEmptyElements(child); + + // Check if the child is an element and is empty + if (child is Aspose.Html.Dom.Element element) + { + bool hasNoChildren = element.FirstChild == null; + bool hasNoText = string.IsNullOrWhiteSpace(element.TextContent); + if (hasNoChildren && hasNoText) + { + node.RemoveChild(child); + } + } + + child = next; + } + } +} \ No newline at end of file diff --git a/html-navigation/detect-broken-links-by-sending-http-head-requests-to-each-extracted-url-and-logging-failures.cs b/html-navigation/detect-broken-links-by-sending-http-head-requests-to-each-extracted-url-and-logging-failures.cs new file mode 100644 index 0000000..c6f4928 --- /dev/null +++ b/html-navigation/detect-broken-links-by-sending-http-head-requests-to-each-extracted-url-and-logging-failures.cs @@ -0,0 +1,69 @@ +// Detect broken links by sending HTTP HEAD requests to each extracted URL and logging failures. + +using System; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content with links + string htmlContent = "" + + "Valid Link" + + "Broken Link" + + ""; + + // Load HTML document from string (using a dummy base URI) + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + List brokenLinks = new List(); + + foreach (Aspose.Html.Dom.Element linkElement in document.Links) + { + string href = linkElement.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + + // Resolve relative URLs against the document's base URI + string absoluteUrl; + try + { + absoluteUrl = new Uri(new Uri(document.BaseURI), href).AbsoluteUri; + } + catch + { + // Skip malformed URLs + continue; + } + + // Send HTTP HEAD request + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(absoluteUrl); + var response = document.Context.Network.Send(request); + + // Consider status codes 400 and above as failures + if ((int)response.StatusCode >= 400) + { + brokenLinks.Add(absoluteUrl); + } + } + + // Log results + Console.WriteLine("Broken links detected:"); + foreach (string url in brokenLinks) + { + Console.WriteLine(url); + } + + if (brokenLinks.Count == 0) + { + Console.WriteLine("No broken links found."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/detect-correct-malformed-tags-missing-closing-brackets-parsing.cs b/html-navigation/detect-correct-malformed-tags-missing-closing-brackets-parsing.cs new file mode 100644 index 0000000..728b74b --- /dev/null +++ b/html-navigation/detect-correct-malformed-tags-missing-closing-brackets-parsing.cs @@ -0,0 +1,34 @@ +// Detect and correct malformed tags such as missing closing brackets during parsing. + +using System; +using Aspose.Html; +using Aspose.Html.Dom; + +class Program +{ + static void Main(string[] args) + { + try + { + // Sample HTML with a missing closing tag + string htmlContent = "

Sample paragraph"; + + // Load HTML content using the two-argument constructor (inline content) + HTMLDocument document = new HTMLDocument(htmlContent, "about:blank"); + + // Retrieve the corrected HTML after parsing + Element rootElement = document.DocumentElement; + string correctedHtml = rootElement.OuterHTML; + + Console.WriteLine("Original HTML:"); + Console.WriteLine(htmlContent); + Console.WriteLine(); + Console.WriteLine("Corrected HTML after parsing:"); + Console.WriteLine(correctedHtml); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/detect-duplicate-meta-tags-retain-first-occurrence-avoid-conflicts.cs b/html-navigation/detect-duplicate-meta-tags-retain-first-occurrence-avoid-conflicts.cs new file mode 100644 index 0000000..f1062e1 --- /dev/null +++ b/html-navigation/detect-duplicate-meta-tags-retain-first-occurrence-avoid-conflicts.cs @@ -0,0 +1,66 @@ +// Detect duplicate meta tags and retain only the first occurrence to avoid conflicts. + +using System; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "" + + "" + + "" + + "" + + "" + + "" + + "

Hello World

"; + + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + var metaElements = document.GetElementsByTagName("meta"); + + var metaList = new List(); + for (int i = 0; i < metaElements.Length; i++) + { + metaList.Add((Aspose.Html.Dom.Element)metaElements[i]); + } + + var seenNames = new HashSet(); + var seenHttpEquiv = new HashSet(); + + foreach (var meta in metaList) + { + string nameAttr = meta.GetAttribute("name"); + if (!string.IsNullOrEmpty(nameAttr)) + { + if (!seenNames.Add(nameAttr)) + { + var parent = meta.ParentNode; + if (parent != null) parent.RemoveChild(meta); + } + continue; + } + + string httpEquivAttr = meta.GetAttribute("http-equiv"); + if (!string.IsNullOrEmpty(httpEquivAttr)) + { + if (!seenHttpEquiv.Add(httpEquivAttr)) + { + var parent = meta.ParentNode; + if (parent != null) parent.RemoveChild(meta); + } + } + } + + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine($"Processed HTML saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/detect_and_extract_comment_nodes_with_todo_markers_for_development_tracking.cs b/html-navigation/detect-extract-all-comment-nodes-containing-todo-markers-development-tracking.cs similarity index 60% rename from html-navigation/detect_and_extract_comment_nodes_with_todo_markers_for_development_tracking.cs rename to html-navigation/detect-extract-all-comment-nodes-containing-todo-markers-development-tracking.cs index fbc2605..9d02a34 100644 --- a/html-navigation/detect_and_extract_comment_nodes_with_todo_markers_for_development_tracking.cs +++ b/html-navigation/detect-extract-all-comment-nodes-containing-todo-markers-development-tracking.cs @@ -12,33 +12,31 @@ static void Main() { try { - // Input and output paths string inputPath = "sample.html"; string outputPath = "todos.txt"; // Create a minimal sample HTML file if it does not exist if (!File.Exists(inputPath)) { - string sampleHtml = ""; + string sampleHtml = "\n\n

Hello

\n"; File.WriteAllText(inputPath, sampleHtml); } // Load the HTML document - using (HTMLDocument document = new HTMLDocument(inputPath)) - { - // Collect TODO comments - List todoComments = new List(); - ExtractTodoComments(document.DocumentElement, todoComments); + HTMLDocument document = new HTMLDocument(inputPath); - // Write extracted TODOs to a file - File.WriteAllLines(outputPath, todoComments); + // Extract TODO comments + List todoComments = new List(); + ExtractTodoComments(document.DocumentElement, todoComments); - // Optionally, display them - Console.WriteLine("Extracted TODO comments:"); - foreach (string comment in todoComments) - { - Console.WriteLine(comment); - } + // Save extracted TODO comments to a file + File.WriteAllLines(outputPath, todoComments); + + // Output to console + Console.WriteLine("Extracted TODO comments:"); + foreach (string comment in todoComments) + { + Console.WriteLine(comment); } } catch (Exception ex) @@ -56,7 +54,7 @@ static void ExtractTodoComments(Node node, List todos) if (child.NodeName == "#comment") { - string commentText = child.NodeValue as string; + string commentText = child.NodeValue; if (!string.IsNullOrEmpty(commentText) && commentText.Contains("TODO")) { todos.Add(commentText.Trim()); diff --git a/html-navigation/detect-extract-inline-svg-elements-save-separate-svg-files.cs b/html-navigation/detect-extract-inline-svg-elements-save-separate-svg-files.cs new file mode 100644 index 0000000..fbff0f1 --- /dev/null +++ b/html-navigation/detect-extract-inline-svg-elements-save-separate-svg-files.cs @@ -0,0 +1,56 @@ +// Detect and extract all inline SVG elements and save them as separate .svg files. + +using System; +using System.IO; +using System.Collections.Generic; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom.Svg; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content containing inline SVG elements + string htmlContent = "" + + "" + + "" + + ""; + + // Load HTML document from the string (using a dummy base URI) + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all SVG elements + Aspose.Html.Collections.HTMLCollection svgs = document.GetElementsByTagName("svg"); + + // Keep track of already processed SVG markup to avoid duplicates + System.Collections.Generic.HashSet seenMarkups = new System.Collections.Generic.HashSet(); + + for (int i = 0; i < svgs.Length; i++) + { + Aspose.Html.HTMLElement svgElement = (Aspose.Html.HTMLElement)svgs[i]; + string markup = svgElement.OuterHTML; + + // Skip duplicate SVGs + if (!seenMarkups.Add(markup)) + continue; + + // Prepare output file path + string fileName = $"svg_{i}.svg"; + string outputPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName); + + // Create an SVG document from the markup and save it + Aspose.Html.Dom.Svg.SVGDocument svgDoc = new Aspose.Html.Dom.Svg.SVGDocument(markup, "about:blank"); + svgDoc.Save(outputPath); + } + + System.Console.WriteLine("SVG extraction completed successfully."); + } + catch (Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/detect_language_attribute_html_tag_set_en_us_if_missing.cs b/html-navigation/detect-language-attribute-html-tag-set-en-us-if-missing.cs similarity index 62% rename from html-navigation/detect_language_attribute_html_tag_set_en_us_if_missing.cs rename to html-navigation/detect-language-attribute-html-tag-set-en-us-if-missing.cs index e910881..ea99baa 100644 --- a/html-navigation/detect_language_attribute_html_tag_set_en_us_if_missing.cs +++ b/html-navigation/detect-language-attribute-html-tag-set-en-us-if-missing.cs @@ -1,25 +1,23 @@ // Detect the language attribute of the HTML tag and set it to “en‑US” if missing. using System; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; class Program { - static void Main() + static void Main(string[] args) { try { - // Sample HTML content without language attribute string htmlContent = "Sample

Hello World

"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, string.Empty); - - // Get the element(s) - Aspose.Html.Collections.HTMLCollection htmlElements = document.GetElementsByTagName("html"); - - for (int i = 0; i < htmlElements.Length; i++) + Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("html"); + for (int i = 0; i < elements.Length; i++) { - Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)htmlElements[i]; + Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)elements[i]; string lang = element.GetAttribute("lang"); if (string.IsNullOrWhiteSpace(lang)) { @@ -27,11 +25,9 @@ static void Main() } } - // Save the modified document string outputPath = "output.html"; document.Save(outputPath); - - Console.WriteLine("Document saved to " + outputPath); + Console.WriteLine("Processed HTML saved to: " + outputPath); } catch (Exception ex) { diff --git a/html-navigation/detect-list-elements-with-tabindex-attributes-evaluate-keyboard-navigation-order.cs b/html-navigation/detect-list-elements-with-tabindex-attributes-evaluate-keyboard-navigation-order.cs new file mode 100644 index 0000000..ced8f14 --- /dev/null +++ b/html-navigation/detect-list-elements-with-tabindex-attributes-evaluate-keyboard-navigation-order.cs @@ -0,0 +1,28 @@ +// Detect and list all elements with tabindex attributes to evaluate keyboard navigation order. + +using System; + +class Program +{ + static void Main() + { + try + { + string html = "Link
Div
"; + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank")) + { + Aspose.Html.Collections.NodeList elements = document.QuerySelectorAll("[tabindex]"); + foreach (Aspose.Html.HTMLElement element in elements) + { + string tag = element.TagName; + string tabindex = element.GetAttribute("tabindex"); + Console.WriteLine($"Tag: {tag}, TabIndex: {tabindex}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/detect-pagination-controls-searching-links-containing-next-or-previous-text.cs b/html-navigation/detect-pagination-controls-searching-links-containing-next-or-previous-text.cs new file mode 100644 index 0000000..8ac66d2 --- /dev/null +++ b/html-navigation/detect-pagination-controls-searching-links-containing-next-or-previous-text.cs @@ -0,0 +1,54 @@ +// Detect pagination controls by searching for links containing “next” or “previous” text. + +using System; +using System.Collections.Generic; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Collections; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "" + + "Next " + + "Previous " + + "Home" + + ""; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + List paginationLinks = new List(); + + foreach (Aspose.Html.Dom.Element linkElement in document.Links) + { + string text = linkElement.TextContent != null ? linkElement.TextContent.Trim() : string.Empty; + if (string.IsNullOrEmpty(text)) + continue; + + if (text.IndexOf("next", StringComparison.OrdinalIgnoreCase) >= 0 || + text.IndexOf("previous", StringComparison.OrdinalIgnoreCase) >= 0) + { + string href = linkElement.GetAttribute("href"); + if (!string.IsNullOrEmpty(href)) + { + paginationLinks.Add($"{text}: {href}"); + } + } + } + + Console.WriteLine("Pagination links found:"); + foreach (string item in paginationLinks) + { + Console.WriteLine(item); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/detect-remove-empty-style-tags-no-css-rules-document.cs b/html-navigation/detect-remove-empty-style-tags-no-css-rules-document.cs new file mode 100644 index 0000000..5796616 --- /dev/null +++ b/html-navigation/detect-remove-empty-style-tags-no-css-rules-document.cs @@ -0,0 +1,37 @@ +// Detect and remove empty style tags that contain no CSS rules in the document. + +using System; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = "

Hello

"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + Aspose.Html.Collections.HTMLCollection styleElements = document.GetElementsByTagName("style"); + + for (int i = styleElements.Length - 1; i >= 0; i--) + { + Aspose.Html.Dom.Element style = (Aspose.Html.Dom.Element)styleElements[i]; + if (string.IsNullOrWhiteSpace(style.TextContent)) + { + if (style.ParentNode != null) + { + style.ParentNode.RemoveChild(style); + } + } + } + + string outputPath = "output.html"; + document.Save(outputPath); + System.Console.WriteLine("Empty

Hello World

"; - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent); - - // Get all + -
Header
-

Paragraph 1

- Span -
    -
  • Item 1
  • -
  • Item 2
  • -
- +
Hello
+

World

+ Sample "; - // Load the HTML document from the string - var document = new Aspose.Html.HTMLDocument(htmlContent); + // Load the HTML document from the string (inline content) + HTMLDocument document = new HTMLDocument(htmlContent, "about:blank"); // Select all elements that have a class attribute - Aspose.Html.Collections.NodeList elements = document.QuerySelectorAll("[class]"); + NodeList elements = document.QuerySelectorAll("[class]"); // Dictionary to hold class name frequencies - var classFrequency = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary classFrequency = new Dictionary(StringComparer.Ordinal); - foreach (Aspose.Html.HTMLElement element in elements) + // Iterate over the selected elements + foreach (HTMLElement element in elements) { string classAttr = element.GetAttribute("class"); if (string.IsNullOrWhiteSpace(classAttr)) continue; + // Split class attribute value into individual class names string[] classes = classAttr.Split(new char[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (string cls in classes) { @@ -52,14 +57,14 @@ static void Main() // Output the histogram Console.WriteLine("CSS Class Frequency Histogram:"); - foreach (var kvp in classFrequency) + foreach (KeyValuePair kvp in classFrequency) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } } catch (Exception ex) { - Console.WriteLine($"Error: {ex.Message}"); + Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/html-navigation/extract-all-data-table-elements-generate-json-arrays-representing-each-table-rows.cs b/html-navigation/extract-all-data-table-elements-generate-json-arrays-representing-each-table-rows.cs new file mode 100644 index 0000000..4f251f9 --- /dev/null +++ b/html-navigation/extract-all-data-table-elements-generate-json-arrays-representing-each-table-rows.cs @@ -0,0 +1,57 @@ +// Extract all data‑table elements and generate JSON arrays representing each table’s rows. + +using System; +using System.Collections.Generic; +using System.Text.Json; + +class Program +{ + static void Main() + { + try + { + string html = @"" + + "" + + "
R1C1R1C2
R2C1R2C2
" + + "
A
" + + ""; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank")) + { + Aspose.Html.Collections.HTMLCollection tables = document.GetElementsByTagName("table"); + for (int t = 0; t < tables.Length; t++) + { + var tableNode = tables[t]; + if (tableNode is Aspose.Html.HTMLTableElement table) + { + var tableData = new List>(); + Aspose.Html.Collections.HTMLCollection rows = table.GetElementsByTagName("tr"); + for (int r = 0; r < rows.Length; r++) + { + var rowNode = rows[r]; + if (rowNode is Aspose.Html.HTMLTableRowElement row) + { + var rowData = new List(); + Aspose.Html.Collections.HTMLCollection cells = row.Cells; + for (int c = 0; c < cells.Length; c++) + { + var cell = cells[c]; + string cellText = cell.TextContent?.Trim(); + rowData.Add(cellText ?? string.Empty); + } + tableData.Add(rowData); + } + } + string json = JsonSerializer.Serialize(tableData, new JsonSerializerOptions { WriteIndented = true }); + Console.WriteLine($"Table {t} JSON:"); + Console.WriteLine(json); + } + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-all-data-table-rows-calculate-sum-numeric-columns-reporting.cs b/html-navigation/extract-all-data-table-rows-calculate-sum-numeric-columns-reporting.cs new file mode 100644 index 0000000..d5b6ff1 --- /dev/null +++ b/html-navigation/extract-all-data-table-rows-calculate-sum-numeric-columns-reporting.cs @@ -0,0 +1,54 @@ +// Extract all data‑table rows and calculate the sum of numeric columns for reporting. + +using System; +using System.Globalization; + +class Program +{ + static void Main() + { + try + { + string html = @" + + + +
10abc
2030
+ "; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank")) + { + double sum = 0; + Aspose.Html.Collections.HTMLCollection tables = document.GetElementsByTagName("table"); + foreach (var tableNode in tables) + { + if (tableNode is Aspose.Html.HTMLTableElement table) + { + Aspose.Html.Collections.HTMLCollection rows = table.GetElementsByTagName("tr"); + foreach (var rowNode in rows) + { + if (rowNode is Aspose.Html.HTMLTableRowElement row) + { + Aspose.Html.Collections.HTMLCollection cells = row.Cells; + foreach (var cell in cells) + { + string cellText = cell.TextContent?.Trim(); + if (double.TryParse(cellText, NumberStyles.Any, CultureInfo.InvariantCulture, out double value)) + { + sum += value; + } + } + } + } + } + } + + Console.WriteLine(sum.ToString(CultureInfo.InvariantCulture)); + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-all-heading-elements-assign-incremental-ids-anchor-linking-within-document.cs b/html-navigation/extract-all-heading-elements-assign-incremental-ids-anchor-linking-within-document.cs new file mode 100644 index 0000000..399d63c --- /dev/null +++ b/html-navigation/extract-all-heading-elements-assign-incremental-ids-anchor-linking-within-document.cs @@ -0,0 +1,63 @@ +// Extract all heading elements and assign incremental IDs for anchor linking within the document. + +using System; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Collections; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content + string htmlContent = "

Title 1

Subtitle

Section

"; + // Load document from string (use two-argument constructor) + HTMLDocument document = new HTMLDocument(htmlContent, "about:blank"); + HTMLElement body = document.Body; + + // Create a list to hold anchor links + HTMLElement ul = (HTMLElement)document.CreateElement("ul"); + + int counter = 1; + string[] headingTags = new string[] { "h1", "h2", "h3", "h4", "h5", "h6" }; + + foreach (string tag in headingTags) + { + HTMLCollection headings = document.GetElementsByTagName(tag); + for (int i = 0; i < headings.Length; i++) + { + HTMLHeadingElement heading = (HTMLHeadingElement)headings[i]; + string id = "heading" + counter; + heading.SetAttribute("id", id); + + // Create list item with anchor linking to the heading + HTMLElement li = (HTMLElement)document.CreateElement("li"); + HTMLAnchorElement a = (HTMLAnchorElement)document.CreateElement("a"); + a.SetAttribute("href", "#" + id); + a.AppendChild(document.CreateTextNode(heading.TextContent)); + li.AppendChild(a); + ul.AppendChild(li); + + counter++; + } + } + + // Insert the list at the beginning of the body + Node firstChild = body.FirstChild; + if (firstChild != null) + body.InsertBefore(ul, firstChild); + else + body.AppendChild(ul); + + // Save the modified document + string outputPath = "output.html"; + document.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-all-hyperlink-href-attributes-from-anchor-tags-to-csv.cs b/html-navigation/extract-all-hyperlink-href-attributes-from-anchor-tags-to-csv.cs new file mode 100644 index 0000000..298f7d0 --- /dev/null +++ b/html-navigation/extract-all-hyperlink-href-attributes-from-anchor-tags-to-csv.cs @@ -0,0 +1,61 @@ +// Extract all hyperlink href attributes from anchor tags and write them to a CSV file. + +using System; +using System.IO; + +class Program +{ + static void Main(string[] args) + { + try + { + // Sample HTML content + string htmlContent = @" + + + Page 1 + Page 2 + Email + No href attribute + + "; + + // Load HTML document from string + using Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all anchor elements + Aspose.Html.Collections.HTMLCollection links = document.GetElementsByTagName("a"); + + // Prepare CSV output + string csvPath = "links.csv"; + using (StreamWriter writer = new StreamWriter(csvPath, false)) + { + // Write CSV header + writer.WriteLine("Href,Text"); + + // Iterate over links and write to CSV + for (int i = 0; i < links.Length; i++) + { + Aspose.Html.Dom.Element link = links[i]; + string href = link.GetAttribute("href"); + string text = link.TextContent != null ? link.TextContent.Trim() : string.Empty; + + if (!string.IsNullOrEmpty(href)) + { + // Escape double quotes in fields + string escapedHref = href.Replace("\"", "\"\""); + string escapedText = text.Replace("\"", "\"\""); + + writer.WriteLine($"\"{escapedHref}\",\"{escapedText}\""); + } + } + } + + Console.WriteLine($"Hyperlink data has been written to '{csvPath}'."); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-all-link-elements-rel-preload-list-resource-urls-performance-audit.cs b/html-navigation/extract-all-link-elements-rel-preload-list-resource-urls-performance-audit.cs new file mode 100644 index 0000000..3085a94 --- /dev/null +++ b/html-navigation/extract-all-link-elements-rel-preload-list-resource-urls-performance-audit.cs @@ -0,0 +1,52 @@ +// Extract all link elements with rel="preload" and list their resource URLs for performance audit. + +using System; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + try + { + string html = @"" + + "" + + "" + + "" + + ""; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank")) + { + Aspose.Html.Collections.HTMLCollection linkElements = document.GetElementsByTagName("link"); + List preloadUrls = new List(); + + for (int i = 0; i < linkElements.Length; i++) + { + Aspose.Html.Dom.Element link = linkElements[i] as Aspose.Html.Dom.Element; + if (link == null) continue; + + string rel = link.GetAttribute("rel"); + if (!string.Equals(rel, "preload", StringComparison.OrdinalIgnoreCase)) + continue; + + string href = link.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + + Aspose.Html.Url resolved = new Aspose.Html.Url(href, document.BaseURI); + preloadUrls.Add(resolved.ToString()); + } + + Console.WriteLine("Preload resource URLs:"); + foreach (string url in preloadUrls) + { + Console.WriteLine(url); + } + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-anchor-elements-open-in-new-window-target-blank-security-review.cs b/html-navigation/extract-anchor-elements-open-in-new-window-target-blank-security-review.cs new file mode 100644 index 0000000..87b55b5 --- /dev/null +++ b/html-navigation/extract-anchor-elements-open-in-new-window-target-blank-security-review.cs @@ -0,0 +1,57 @@ +// Extract all anchor elements that open in a new window (target="_blank") for security review. + +using System; +using System.Collections.Generic; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = @" + + + Example + Test + Open + + "; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + Aspose.Html.Collections.HTMLCollection links = document.GetElementsByTagName("a"); + List> result = new List>(); + + for (int i = 0; i < links.Length; i++) + { + Aspose.Html.Dom.Element link = (Aspose.Html.Dom.Element)links[i]; + string target = link.GetAttribute("target"); + if (string.Equals(target, "_blank", StringComparison.OrdinalIgnoreCase)) + { + string href = link.GetAttribute("href"); + string text = link.TextContent != null ? link.TextContent.Trim() : string.Empty; + if (!string.IsNullOrEmpty(href)) + { + var item = new Dictionary + { + { "href", href }, + { "text", text } + }; + result.Add(item); + } + } + } + + foreach (var item in result) + { + Console.WriteLine($"Href: {item["href"]}, Text: {item["text"]}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-author-meta-tag-value-store-for-content-attribution.cs b/html-navigation/extract-author-meta-tag-value-store-for-content-attribution.cs new file mode 100644 index 0000000..8f0d1df --- /dev/null +++ b/html-navigation/extract-author-meta-tag-value-store-for-content-attribution.cs @@ -0,0 +1,35 @@ +// Extract the value of the author meta tag and store it for content attribution. + +namespace Example +{ + class Program + { + static void Main(string[] args) + { + try + { + string htmlContent = "Sample

Hello World

"; + byte[] bytes = System.Text.Encoding.UTF8.GetBytes(htmlContent); + using (var inputStream = new System.IO.MemoryStream(bytes)) + using (var document = new Aspose.Html.HTMLDocument(inputStream, "about:blank")) + { + var metaElements = document.GetElementsByTagName("meta"); + string author = null; + foreach (Aspose.Html.Dom.Element meta in metaElements) + { + if (meta.GetAttribute("name") == "author") + { + author = meta.GetAttribute("content"); + break; + } + } + System.Console.WriteLine("Author: " + (author ?? "Not found")); + } + } + catch (System.Exception ex) + { + System.Console.WriteLine(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-breadcrumb-navigation-links-locating-ordered-list-elements-specific-class-names.cs b/html-navigation/extract-breadcrumb-navigation-links-locating-ordered-list-elements-specific-class-names.cs new file mode 100644 index 0000000..95eec82 --- /dev/null +++ b/html-navigation/extract-breadcrumb-navigation-links-locating-ordered-list-elements-specific-class-names.cs @@ -0,0 +1,29 @@ +// Extract breadcrumb navigation links by locating ordered list elements with specific class names. + +namespace Example +{ + class Program + { + static void Main(string[] args) + { + try + { + System.String html = ""; + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank")) + { + Aspose.Html.Collections.NodeList links = document.QuerySelectorAll("ol.breadcrumb a"); + foreach (Aspose.Html.HTMLElement link in links) + { + System.String href = link.GetAttribute("href"); + System.String text = link.TextContent != null ? link.TextContent.Trim() : System.String.Empty; + System.Console.WriteLine($"Text: {text}, Href: {href}"); + } + } + } + catch (System.Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-canonical-link-element-href-value-seo-analysis-document.cs b/html-navigation/extract-canonical-link-element-href-value-seo-analysis-document.cs new file mode 100644 index 0000000..25e1137 --- /dev/null +++ b/html-navigation/extract-canonical-link-element-href-value-seo-analysis-document.cs @@ -0,0 +1,30 @@ +// Extract the canonical link element href value for SEO analysis from the document. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "

Hello World

"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + Aspose.Html.Collections.HTMLCollection linkElements = document.GetElementsByTagName("link"); + for (int i = 0; i < linkElements.Length; i++) + { + Aspose.Html.Dom.Element link = linkElements[i]; + string rel = link.GetAttribute("rel"); + if (!string.IsNullOrEmpty(rel) && rel.Equals("canonical", StringComparison.OrdinalIgnoreCase)) + { + string href = link.GetAttribute("href"); + Console.WriteLine($"Canonical href: {href}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-charset-meta-tag-value-and-ensure-it-matches-file-encoding.cs b/html-navigation/extract-charset-meta-tag-value-and-ensure-it-matches-file-encoding.cs new file mode 100644 index 0000000..b9286d5 --- /dev/null +++ b/html-navigation/extract-charset-meta-tag-value-and-ensure-it-matches-file-encoding.cs @@ -0,0 +1,47 @@ +// Extract the value of the charset meta tag and ensure it matches the file encoding. + +using System; +using System.IO; +using System.Text; +using Aspose.Html; +using Aspose.Html.Dom; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "TestHello"; + byte[] bytes = Encoding.UTF8.GetBytes(htmlContent); + string outputPath = "output.html"; + + using (var inputStream = new MemoryStream(bytes)) + using (var document = new Aspose.Html.HTMLDocument(inputStream, "about:blank")) + { + var metaElements = document.GetElementsByTagName("meta"); + + foreach (Aspose.Html.Dom.Element meta in metaElements) + { + string charset = meta.GetAttribute("charset"); + if (!string.IsNullOrEmpty(charset)) + { + string expected = Encoding.UTF8.WebName; // "utf-8" + if (!string.Equals(charset, expected, StringComparison.OrdinalIgnoreCase)) + { + meta.SetAttribute("charset", expected); + } + } + } + + document.Save(outputPath); + } + + Console.WriteLine("Processing completed. Output saved to " + Path.GetFullPath(outputPath)); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-csrf-token-hidden-input-values-from-forms-for-security-testing.cs b/html-navigation/extract-csrf-token-hidden-input-values-from-forms-for-security-testing.cs new file mode 100644 index 0000000..c71d2b6 --- /dev/null +++ b/html-navigation/extract-csrf-token-hidden-input-values-from-forms-for-security-testing.cs @@ -0,0 +1,45 @@ +// Extract CSRF token hidden input values from forms for security testing purposes. + +using System; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + string htmlContent = @" +
+ + + +
+ "; + + // Load HTML from string using two‑argument constructor (content, baseUri) + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all input elements + Aspose.Html.Collections.HTMLCollection inputElements = document.GetElementsByTagName("input"); + + foreach (Aspose.Html.HTMLElement input in inputElements) + { + string type = input.GetAttribute("type"); + if (!string.IsNullOrEmpty(type) && type.Equals("hidden", StringComparison.OrdinalIgnoreCase)) + { + string name = input.GetAttribute("name"); + if (!string.IsNullOrEmpty(name) && name.IndexOf("csrf", StringComparison.OrdinalIgnoreCase) >= 0) + { + string value = input.GetAttribute("value"); + Console.WriteLine($"CSRF token found: name=\"{name}\", value=\"{value}\""); + } + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-email-addresses-from-mailto-links-compile-plain-text-list.cs b/html-navigation/extract-email-addresses-from-mailto-links-compile-plain-text-list.cs new file mode 100644 index 0000000..1dbe58d --- /dev/null +++ b/html-navigation/extract-email-addresses-from-mailto-links-compile-plain-text-list.cs @@ -0,0 +1,55 @@ +// Extract email addresses from mailto links and compile them into a plain‑text list. + +using System; +using System.Collections.Generic; +using Aspose.Html; +using Aspose.Html.Dom; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = "" + + "John " + + "Jane " + + "Link" + + ""; + + // Load HTML from string using two-argument constructor + HTMLDocument document = new HTMLDocument(htmlContent, "about:blank"); + + List emailList = new List(); + + foreach (Element linkElement in document.Links) + { + string href = linkElement.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + + if (href.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)) + { + string emailPart = href.Substring(7); + int queryIndex = emailPart.IndexOf('?'); + if (queryIndex >= 0) + emailPart = emailPart.Substring(0, queryIndex); + emailPart = emailPart.Trim(); + + if (!string.IsNullOrEmpty(emailPart) && !emailList.Contains(emailPart)) + emailList.Add(emailPart); + } + } + + Console.WriteLine("Extracted email addresses:"); + foreach (string email in emailList) + { + Console.WriteLine(email); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-embedded-video-source-urls-from-iframe-elements-media-cataloging.cs b/html-navigation/extract-embedded-video-source-urls-from-iframe-elements-media-cataloging.cs new file mode 100644 index 0000000..e536a84 --- /dev/null +++ b/html-navigation/extract-embedded-video-source-urls-from-iframe-elements-media-cataloging.cs @@ -0,0 +1,28 @@ +// Extract embedded video source URLs from iframe elements for the media cataloging. + +using System; + +class Program +{ + static void Main() + { + try + { + string html = ""; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank"); + Aspose.Html.Collections.HTMLCollection iframes = document.GetElementsByTagName("iframe"); + for (int i = 0; i < iframes.Length; i++) + { + Aspose.Html.Dom.Element iframe = (Aspose.Html.Dom.Element)iframes[i]; + string src = iframe.GetAttribute("src"); + if (string.IsNullOrEmpty(src)) continue; + Aspose.Html.Url absoluteUrl = new Aspose.Html.Url(src, document.BaseURI); + Console.WriteLine(absoluteUrl.ToString()); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract_heading_tags_h1_h6_build_nested_table_of_contents_json_structure.cs b/html-navigation/extract-heading-tags-h1-h6-and-build-nested-table-of-contents-structure-json.cs similarity index 79% rename from html-navigation/extract_heading_tags_h1_h6_build_nested_table_of_contents_json_structure.cs rename to html-navigation/extract-heading-tags-h1-h6-and-build-nested-table-of-contents-structure-json.cs index df9e459..a6c4462 100644 --- a/html-navigation/extract_heading_tags_h1_h6_build_nested_table_of_contents_json_structure.cs +++ b/html-navigation/extract-heading-tags-h1-h6-and-build-nested-table-of-contents-structure-json.cs @@ -4,44 +4,35 @@ using System.IO; using System.Collections.Generic; using System.Text.Json; +using Aspose.Html; -class Program +class OutlineNode { - class OutlineNode - { - public string Text { get; set; } - public int Level { get; set; } - public List Children { get; set; } - } + public string Text { get; set; } + public int Level { get; set; } + public List Children { get; set; } +} +class Program +{ static void Main() { try { - string inputFolder = "Input"; - string outputFolder = "Output"; + string inputFolder = "InputHtml"; + string outputFolder = "OutputJson"; if (!Directory.Exists(inputFolder)) Directory.CreateDirectory(inputFolder); if (!Directory.Exists(outputFolder)) Directory.CreateDirectory(outputFolder); - // Create a minimal sample HTML file if none exist + // Create a sample HTML file if none exist if (Directory.GetFiles(inputFolder, "*.html").Length == 0) { string samplePath = Path.Combine(inputFolder, "sample.html"); - File.WriteAllText(samplePath, -@" -Sample - -

Chapter 1

-

Section 1.1

-

Subsection 1.1.1

-

Section 1.2

-

Chapter 2

-

Section 2.1

- -"); + string sampleContent = "

Title

Section

Subsection

"; + File.WriteAllText(samplePath, sampleContent); } foreach (string htmlPath in Directory.GetFiles(inputFolder, "*.html")) @@ -81,8 +72,6 @@ static void Main() File.WriteAllText(jsonPath, json); } } - - Console.WriteLine("TOC extraction completed successfully."); } catch (Exception ex) { diff --git a/html-navigation/extract-link-elements-rel-icon-verify-file-formats-favicon-compliance.cs b/html-navigation/extract-link-elements-rel-icon-verify-file-formats-favicon-compliance.cs new file mode 100644 index 0000000..52595df --- /dev/null +++ b/html-navigation/extract-link-elements-rel-icon-verify-file-formats-favicon-compliance.cs @@ -0,0 +1,71 @@ +// Extract all link elements with rel="icon" and verify their file formats for favicon compliance. + +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Net; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = "" + + "" + + "" + + "" + + ""; + + // Load HTML from string with a dummy base URI + HTMLDocument document = new HTMLDocument(htmlContent, "about:blank"); + + List invalidIcons = new List(); + + foreach (Element linkElement in document.Links) + { + string rel = linkElement.GetAttribute("rel"); + if (string.IsNullOrEmpty(rel) || !rel.Equals("icon", StringComparison.OrdinalIgnoreCase)) + continue; + + string href = linkElement.GetAttribute("href"); + if (string.IsNullOrEmpty(href)) + continue; + + // Resolve the URL against the document's base URI + Url resolvedUrl = new Url(href, document.BaseURI); + + // Determine file extension + string extension = Path.GetExtension(resolvedUrl.ToString()).ToLowerInvariant(); + + bool isValid = extension == ".ico" || extension == ".png" || extension == ".svg"; + + Console.WriteLine($"Icon: {resolvedUrl} - {(isValid ? "Valid" : "Invalid")}"); + + if (!isValid) + { + invalidIcons.Add(resolvedUrl.ToString()); + } + } + + if (invalidIcons.Count > 0) + { + Console.WriteLine("\nInvalid favicon links found:"); + foreach (string url in invalidIcons) + { + Console.WriteLine(url); + } + } + else + { + Console.WriteLine("\nAll favicon links are compliant."); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-meta-description-content-and-summarize-length-for-content-quality-checks.cs b/html-navigation/extract-meta-description-content-and-summarize-length-for-content-quality-checks.cs new file mode 100644 index 0000000..c5f743e --- /dev/null +++ b/html-navigation/extract-meta-description-content-and-summarize-length-for-content-quality-checks.cs @@ -0,0 +1,72 @@ +// Extract all meta description content and summarize its length for content quality checks. + +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; + +class Program +{ + static void Main() + { + try + { + string inputPath = "sample.html"; + + if (!File.Exists(inputPath)) + { + string sampleHtml = @" + + + + + + + +

Hello World!

+ +"; + File.WriteAllText(inputPath, sampleHtml); + } + + using (HTMLDocument document = new HTMLDocument(inputPath)) + { + HTMLCollection metaElements = document.GetElementsByTagName("meta"); + List descriptions = new List(); + for (int i = 0; i < metaElements.Length; i++) + { + HTMLElement element = metaElements[i] as HTMLElement; + if (element == null) + continue; + + string nameAttr = element.GetAttribute("name"); + if (string.IsNullOrEmpty(nameAttr)) + continue; + + if (nameAttr.Equals("description", StringComparison.OrdinalIgnoreCase)) + { + string content = element.GetAttribute("content") ?? string.Empty; + descriptions.Add(content); + Console.WriteLine($"Description: \"{content}\""); + Console.WriteLine($"Length: {content.Length}"); + } + } + + int totalLength = 0; + foreach (string desc in descriptions) + { + totalLength += desc.Length; + } + + Console.WriteLine($"Total number of description meta tags: {descriptions.Count}"); + Console.WriteLine($"Combined length of all descriptions: {totalLength}"); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-meta-viewport-values-verify-width-device-width-responsive-design.cs b/html-navigation/extract-meta-viewport-values-verify-width-device-width-responsive-design.cs new file mode 100644 index 0000000..a2147c3 --- /dev/null +++ b/html-navigation/extract-meta-viewport-values-verify-width-device-width-responsive-design.cs @@ -0,0 +1,61 @@ +// Extract all meta viewport values and verify they contain width=device‑width for responsive design. + +using System; +using Aspose.Html; + +class Program +{ + static void Main(string[] args) + { + try + { + // Sample HTML content with meta viewport tags + string htmlContent = @" + + + + + + + +

Hello, world!

+ + "; + + // Load HTML document from string (inline content) + using (HTMLDocument document = new HTMLDocument(htmlContent, "about:blank")) + { + // Get all elements + Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("meta"); + + bool viewportFound = false; + + for (int i = 0; i < elements.Length; i++) + { + Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)elements[i]; + string nameAttr = element.GetAttribute("name"); + if (!string.IsNullOrEmpty(nameAttr) && + string.Equals(nameAttr, "viewport", StringComparison.OrdinalIgnoreCase)) + { + viewportFound = true; + string contentAttr = element.GetAttribute("content") ?? string.Empty; + bool hasWidthDeviceWidth = contentAttr + .IndexOf("width=device-width", StringComparison.OrdinalIgnoreCase) >= 0; + + Console.WriteLine($"Viewport meta tag content: \"{contentAttr}\""); + Console.WriteLine($"Contains width=device-width: {hasWidthDeviceWidth}"); + } + } + + if (!viewportFound) + { + Console.WriteLine("No meta viewport tags were found in the document."); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-open-graph-meta-tags-output-dictionary-social-media-integration.cs b/html-navigation/extract-open-graph-meta-tags-output-dictionary-social-media-integration.cs new file mode 100644 index 0000000..0027d1a --- /dev/null +++ b/html-navigation/extract-open-graph-meta-tags-output-dictionary-social-media-integration.cs @@ -0,0 +1,60 @@ +// Extract Open Graph meta tags and output them as a dictionary for social media integration. + +using System; +using System.Collections.Generic; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content with Open Graph meta tags + string htmlContent = @" + + + + + + + + +

Hello World

+ + "; + + // Load HTML document from the string (using a dummy base URI) + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + // Collection to hold Open Graph meta tags + Dictionary openGraphTags = new Dictionary(); + + // Get all elements + Aspose.Html.Collections.HTMLCollection metaElements = document.GetElementsByTagName("meta"); + + for (int i = 0; i < metaElements.Length; i++) + { + Aspose.Html.HTMLElement meta = (Aspose.Html.HTMLElement)metaElements[i]; + string property = meta.GetAttribute("property"); + if (!string.IsNullOrEmpty(property) && property.StartsWith("og:")) + { + string content = meta.GetAttribute("content") ?? string.Empty; + openGraphTags[property] = content; + } + } + + // Output the extracted Open Graph tags + Console.WriteLine("Extracted Open Graph meta tags:"); + foreach (var kvp in openGraphTags) + { + Console.WriteLine($"{kvp.Key} = {kvp.Value}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-robots-meta-tag-value-indexing-directives.cs b/html-navigation/extract-robots-meta-tag-value-indexing-directives.cs new file mode 100644 index 0000000..e229933 --- /dev/null +++ b/html-navigation/extract-robots-meta-tag-value-indexing-directives.cs @@ -0,0 +1,39 @@ +// Extract the value of the robots meta tag to determine indexing directives. + +using System; + +class Program +{ + static void Main() + { + try + { + string html = "Test

Hello

"; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "about:blank"); + Aspose.Html.Collections.HTMLCollection metaElements = document.GetElementsByTagName("meta"); + string robotsContent = null; + for (int i = 0; i < metaElements.Length; i++) + { + Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)metaElements[i]; + string nameAttr = element.GetAttribute("name"); + if (!string.IsNullOrEmpty(nameAttr) && nameAttr.Equals("robots", StringComparison.OrdinalIgnoreCase)) + { + robotsContent = element.GetAttribute("content"); + break; + } + } + if (robotsContent != null) + { + Console.WriteLine("Robots meta tag content: " + robotsContent); + } + else + { + Console.WriteLine("Robots meta tag not found."); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-style-attribute-values-create-stylesheet-file-equivalent-css-rules.cs b/html-navigation/extract-style-attribute-values-create-stylesheet-file-equivalent-css-rules.cs new file mode 100644 index 0000000..4b8dc4c --- /dev/null +++ b/html-navigation/extract-style-attribute-values-create-stylesheet-file-equivalent-css-rules.cs @@ -0,0 +1,63 @@ +// Extract all style attribute values and create a stylesheet file containing equivalent CSS rules. + +using System; +using System.Text; +using System.IO; + +class Program +{ + static void Main() + { + try + { + string htmlContent = @" + + + + Sample + + + +

Paragraph 1

+ Span + +"; + + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + var elements = document.QuerySelectorAll("[style]"); + + var cssBuilder = new StringBuilder(); + + for (int i = 0; i < elements.Length; i++) + { + var element = (Aspose.Html.HTMLElement)elements[i]; + string styleValue = element.GetAttribute("style"); + if (string.IsNullOrEmpty(styleValue)) + continue; + + string selector = $"{element.TagName.ToLowerInvariant()}_style_{i + 1}"; + cssBuilder.AppendLine($"{selector} {{{styleValue}}}"); + } + + string cssPath = "extracted-styles.css"; + File.WriteAllText(cssPath, cssBuilder.ToString()); + + var head = document.QuerySelector("head"); + if (head != null) + { + var link = document.CreateElement("link"); + link.SetAttribute("rel", "stylesheet"); + link.SetAttribute("href", cssPath); + head.AppendChild(link); + } + + string outputHtmlPath = "output.html"; + document.Save(outputHtmlPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-table-data-html-tables-export-each-table-separate-csv-file.cs b/html-navigation/extract-table-data-html-tables-export-each-table-separate-csv-file.cs new file mode 100644 index 0000000..f94b79b --- /dev/null +++ b/html-navigation/extract-table-data-html-tables-export-each-table-separate-csv-file.cs @@ -0,0 +1,76 @@ +// Extract table data from HTML tables and export each table to a separate CSV file. + +using System; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content with two tables + string htmlContent = "" + + "" + + "" + + "" + + "" + + "
NameAge
Alice30
Bob25
" + + "" + + "" + + "" + + "
Item110
Item220
" + + ""; + + // Load HTML document from string (inline content) + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all table elements + Aspose.Html.Collections.HTMLCollection tables = document.GetElementsByTagName("table"); + + int tableIndex = 1; + foreach (var tableNode in tables) + { + if (tableNode is Aspose.Html.HTMLTableElement table) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + + // Get all rows in the current table + Aspose.Html.Collections.HTMLCollection rows = table.GetElementsByTagName("tr"); + foreach (var rowNode in rows) + { + if (rowNode is Aspose.Html.HTMLTableRowElement row) + { + Aspose.Html.Collections.HTMLCollection cells = row.Cells; + bool firstCell = true; + foreach (var cell in cells) + { + string cellText = cell.TextContent?.Trim() ?? ""; + // Escape commas and double quotes for CSV + if (cellText.Contains("\"") || cellText.Contains(",")) + { + cellText = $"\"{cellText.Replace("\"", "\"\"")}\""; + } + + if (!firstCell) + sb.Append(","); + + sb.Append(cellText); + firstCell = false; + } + sb.AppendLine(); + } + } + + string outputPath = $"Table_{tableIndex}.csv"; + System.IO.File.WriteAllText(outputPath, sb.ToString()); + System.Console.WriteLine($"Table {tableIndex} saved to {outputPath}"); + tableIndex++; + } + } + } + catch (Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract-theme-color-meta-tag-value-for-use-in-progressive-web-app-configuration.cs b/html-navigation/extract-theme-color-meta-tag-value-for-use-in-progressive-web-app-configuration.cs new file mode 100644 index 0000000..1514921 --- /dev/null +++ b/html-navigation/extract-theme-color-meta-tag-value-for-use-in-progressive-web-app-configuration.cs @@ -0,0 +1,31 @@ +// Extract the theme‑color meta tag value for use in progressive web app configuration. + +using System; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = ""; + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + Aspose.Html.Collections.NodeList metaElements = document.QuerySelectorAll("meta[name='theme-color']"); + if (metaElements.Length > 0) + { + Aspose.Html.HTMLElement metaTag = (Aspose.Html.HTMLElement)metaElements[0]; + string themeColor = metaTag.GetAttribute("content"); + System.Console.WriteLine("Theme color meta tag value: " + themeColor); + } + else + { + System.Console.WriteLine("Theme color meta tag not found."); + } + } + catch (Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/extract_all_anchor_elements_open_in_new_window_target_blank_security_review.cs b/html-navigation/extract_all_anchor_elements_open_in_new_window_target_blank_security_review.cs deleted file mode 100644 index acc7f1c..0000000 --- a/html-navigation/extract_all_anchor_elements_open_in_new_window_target_blank_security_review.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Extract all anchor elements that open in a new window (target="_blank") for security review. - -using System; - -class Program -{ - static void Main() - { - try - { - string html = "" + - "Example" + - "Test" + - "Open" + - ""; - - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html)) - { - Aspose.Html.Collections.NodeList elements = document.QuerySelectorAll("a[target='_blank']"); - foreach (Aspose.Html.HTMLElement element in elements) - { - string href = element.GetAttribute("href"); - string text = element.TextContent != null ? element.TextContent.Trim() : string.Empty; - if (!string.IsNullOrEmpty(href)) - { - Console.WriteLine($"Href: {href}, Text: {text}"); - } - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_all_data_table_elements_generate_json_arrays_representing_each_table_rows.cs b/html-navigation/extract_all_data_table_elements_generate_json_arrays_representing_each_table_rows.cs deleted file mode 100644 index 8578a24..0000000 --- a/html-navigation/extract_all_data_table_elements_generate_json_arrays_representing_each_table_rows.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Extract all data‑table elements and generate JSON arrays representing each table’s rows. - -using System; -using System.Collections.Generic; -using System.Text.Json; - -namespace ExtractTablesToJson -{ - class Program - { - static void Main() - { - try - { - string htmlContent = @"" + - "" + - "
Header1Header2
Row1Col1Row1Col2
" + - "
A
B
" + - ""; - - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent)) - { - Aspose.Html.Collections.HTMLCollection tables = document.GetElementsByTagName("table"); - for (int t = 0; t < tables.Length; t++) - { - Aspose.Html.HTMLElement htmlTable = tables[t] as Aspose.Html.HTMLElement; - if (htmlTable is Aspose.Html.HTMLTableElement table) - { - Aspose.Html.Collections.HTMLCollection rows = table.GetElementsByTagName("tr"); - var tableData = new List>(); - for (int r = 0; r < rows.Length; r++) - { - if (rows[r] is Aspose.Html.HTMLTableRowElement row) - { - Aspose.Html.Collections.HTMLCollection cells = row.Cells; - var rowData = new List(); - for (int c = 0; c < cells.Length; c++) - { - var cell = cells[c]; - string cellText = cell.TextContent?.Trim(); - rowData.Add(cellText ?? string.Empty); - } - tableData.Add(rowData); - } - } - string json = JsonSerializer.Serialize(tableData, new JsonSerializerOptions { WriteIndented = true }); - Console.WriteLine($"Table {t + 1} JSON:"); - Console.WriteLine(json); - } - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_all_data_table_rows_and_calculate_sum_of_numeric_columns_for_reporting.cs b/html-navigation/extract_all_data_table_rows_and_calculate_sum_of_numeric_columns_for_reporting.cs deleted file mode 100644 index 88908f6..0000000 --- a/html-navigation/extract_all_data_table_rows_and_calculate_sum_of_numeric_columns_for_reporting.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Extract all data‑table rows and calculate the sum of numeric columns for reporting. - -using System; -using System.Globalization; - -class Program -{ - static void Main() - { - try - { - string html = "
ItemPrice
Apple1.5
Banana2.0
"; - - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, ""); - - Aspose.Html.Collections.HTMLCollection tables = document.GetElementsByTagName("table"); - - double sum = 0; - - foreach (var tableNode in tables) - { - if (tableNode is Aspose.Html.HTMLTableElement table) - { - Aspose.Html.Collections.HTMLCollection rows = table.GetElementsByTagName("tr"); - foreach (var rowNode in rows) - { - if (rowNode is Aspose.Html.HTMLTableRowElement row) - { - Aspose.Html.Collections.HTMLCollection cells = row.Cells; - foreach (var cell in cells) - { - string cellText = cell.TextContent?.Trim(); - if (double.TryParse(cellText, NumberStyles.Any, CultureInfo.InvariantCulture, out double value)) - { - sum += value; - } - } - } - } - } - } - - System.Console.WriteLine(sum.ToString(CultureInfo.InvariantCulture)); - } - catch (Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_all_style_attribute_values_create_stylesheet_file_containing_equivalent_css_rules.cs b/html-navigation/extract_all_style_attribute_values_create_stylesheet_file_containing_equivalent_css_rules.cs deleted file mode 100644 index eaf2861..0000000 --- a/html-navigation/extract_all_style_attribute_values_create_stylesheet_file_containing_equivalent_css_rules.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Extract all style attribute values and create a stylesheet file containing equivalent CSS rules. - -using System; -using System.IO; -using System.Text; - -class Program -{ - static void Main(string[] args) - { - try - { - // Sample HTML content with inline styles - string htmlContent = @" - - - -
Test
-

Paragraph

- Span text - -"; - - // Write the sample HTML to a temporary file - string htmlPath = "sample.html"; - File.WriteAllText(htmlPath, htmlContent, Encoding.UTF8); - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); - - // Select all elements that have a style attribute - Aspose.Html.Collections.NodeList elements = document.QuerySelectorAll("[style]"); - - // Build CSS rules from the extracted style attributes - StringBuilder cssBuilder = new StringBuilder(); - - foreach (Aspose.Html.HTMLElement element in elements) - { - // Get the tag name of the element - string tagName = ((Aspose.Html.Dom.Element)element).TagName; - - // Get the value of the style attribute - string styleValue = element.GetAttribute("style"); - - // Append a CSS rule for this tag - cssBuilder.AppendLine($"{tagName} {{{styleValue}}}"); - } - - // Write the generated CSS to a stylesheet file - string cssPath = "extracted-styles.css"; - File.WriteAllText(cssPath, cssBuilder.ToString(), Encoding.UTF8); - - Console.WriteLine($"CSS stylesheet generated at: {Path.GetFullPath(cssPath)}"); - } - catch (Exception ex) - { - Console.WriteLine("An error occurred: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_author_meta_tag_value_and_store_for_content_attribution.cs b/html-navigation/extract_author_meta_tag_value_and_store_for_content_attribution.cs deleted file mode 100644 index 4c25ccd..0000000 --- a/html-navigation/extract_author_meta_tag_value_and_store_for_content_attribution.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Extract the value of the author meta tag and store it for content attribution. - -using System; -using System.Text; -using System.IO; -using Aspose.Html; -using Aspose.Html.Dom; -using Aspose.Html.Collections; - -class Program -{ - static void Main(string[] args) - { - try - { - string htmlContent = ""; - byte[] bytes = System.Text.Encoding.UTF8.GetBytes(htmlContent); - using (var inputStream = new System.IO.MemoryStream(bytes)) - using (var document = new Aspose.Html.HTMLDocument(inputStream, string.Empty)) - { - var metaElements = document.GetElementsByTagName("meta"); - string author = string.Empty; - - foreach (Aspose.Html.Dom.Element meta in metaElements) - { - if (meta.GetAttribute("name") == "author") - { - author = meta.GetAttribute("content"); - break; - } - } - - System.Console.WriteLine("Author meta tag value: " + author); - - string outputPath = "output.html"; - document.Save(outputPath); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_breadcrumb_navigation_links_locating_ordered_list_elements_specific_class_names.cs b/html-navigation/extract_breadcrumb_navigation_links_locating_ordered_list_elements_specific_class_names.cs deleted file mode 100644 index 2c1b131..0000000 --- a/html-navigation/extract_breadcrumb_navigation_links_locating_ordered_list_elements_specific_class_names.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Extract breadcrumb navigation links by locating ordered list elements with specific class names. - -using System; - -class Program -{ - static void Main() - { - try - { - string html = "
  1. Home
  2. Products
  3. Current
"; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, "")) - { - var breadcrumbLists = document.QuerySelectorAll("ol.breadcrumb"); - var results = new System.Collections.Generic.List>(); - foreach (Aspose.Html.HTMLElement list in breadcrumbLists) - { - var links = list.QuerySelectorAll("a"); - foreach (Aspose.Html.HTMLElement link in links) - { - string href = link.GetAttribute("href"); - string text = link.TextContent != null ? link.TextContent.Trim() : string.Empty; - if (!string.IsNullOrEmpty(href)) - { - var dict = new System.Collections.Generic.Dictionary(); - dict["href"] = href; - dict["text"] = text; - results.Add(dict); - } - } - } - string json = System.Text.Json.JsonSerializer.Serialize(results, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }); - System.Console.WriteLine(json); - } - } - catch (System.Exception ex) - { - System.Console.Error.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_canonical_link_element_href_value_for_seo_analysis_from_document.cs b/html-navigation/extract_canonical_link_element_href_value_for_seo_analysis_from_document.cs deleted file mode 100644 index 466ac9b..0000000 --- a/html-navigation/extract_canonical_link_element_href_value_for_seo_analysis_from_document.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Extract the canonical link element href value for SEO analysis from the document. - -using System; -using System.Collections.Generic; -using System.IO; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; -using Aspose.Html.Net; - -class Program -{ - static void Main() - { - try - { - // Prepare a minimal HTML file - string htmlContent = @" - - - - - - - - - -
Valid Link
Invalid Link
- - Another Valid Link - -"; - string inputPath = Path.Combine(Path.GetTempPath(), "sample.html"); - File.WriteAllText(inputPath, htmlContent); - - // Load the document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - - // 1. Extract links from tables - HTMLCollection tables = document.GetElementsByTagName("table"); - var tableLinks = new List>(); - for (int t = 0; t < tables.Length; t++) - { - HTMLElement htmlTable = tables[t] as HTMLElement; - if (htmlTable != null) - { - HTMLCollection links = htmlTable.GetElementsByTagName("a"); - for (int i = 0; i < links.Length; i++) - { - Element link = links[i] as Element; - string href = link.GetAttribute("href"); - string text = link.TextContent != null ? link.TextContent.Trim() : string.Empty; - if (!string.IsNullOrEmpty(href)) - { - var item = new Dictionary - { - { "href", href }, - { "text", text } - }; - tableLinks.Add(item); - } - } - } - } - - Console.WriteLine("Links found inside tables:"); - foreach (var dict in tableLinks) - { - Console.WriteLine($" href: {dict["href"]}, text: {dict["text"]}"); - } - - // 2. Find broken links in the whole document - List brokenLinks = new List(); - foreach (Element linkElement in document.Links) - { - string href = linkElement.GetAttribute("href"); - if (string.IsNullOrEmpty(href)) - continue; - - Url resolvedUrl = new Url(href, document.BaseURI); - RequestMessage request = new RequestMessage(resolvedUrl); - ResponseMessage response = document.Context.Network.Send(request); - if ((int)response.StatusCode >= 400) - { - brokenLinks.Add(resolvedUrl.ToString()); - } - } - - Console.WriteLine("\nBroken links:"); - foreach (string bl in brokenLinks) - { - Console.WriteLine($" {bl}"); - } - - // 3. List script src attributes - HTMLCollection scriptElements = document.GetElementsByTagName("script"); - Console.WriteLine("\nScript sources:"); - for (int i = 0; i < scriptElements.Length; i++) - { - Element scriptElement = scriptElements[i] as Element; - string src = scriptElement.GetAttribute("src"); - if (!string.IsNullOrEmpty(src)) - { - Console.WriteLine($" {src}"); - } - } - - // 4. List image sources - HTMLCollection images = document.GetElementsByTagName("img"); - Console.WriteLine("\nImage sources:"); - for (int i = 0; i < images.Length; i++) - { - Element imageElement = images[i] as Element; - string src = imageElement.GetAttribute("src"); - if (!string.IsNullOrEmpty(src)) - { - Console.WriteLine($" {src}"); - } - } - - // 5. Query selector example - var elements = document.QuerySelectorAll("a"); - Console.WriteLine("\nAll anchor elements via QuerySelectorAll:"); - foreach (HTMLElement element in elements) - { - Console.WriteLine($" href: {element.GetAttribute("href")}, text: {element.TextContent?.Trim()}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_charset_meta_tag_value_and_ensure_matches_file_encoding.cs b/html-navigation/extract_charset_meta_tag_value_and_ensure_matches_file_encoding.cs deleted file mode 100644 index f62ace0..0000000 --- a/html-navigation/extract_charset_meta_tag_value_and_ensure_matches_file_encoding.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Extract the value of the charset meta tag and ensure it matches the file encoding. - -using System; - -class Program -{ - static void Main() - { - try - { - string sourcePath = "sample.html"; - string outputPath = "result.html"; - - // Create a sample HTML file with a mismatched charset declaration. - string sampleHtml = "TestHello World"; - System.IO.File.WriteAllText(sourcePath, sampleHtml, System.Text.Encoding.GetEncoding("windows-1252")); - - // Read the file using its actual encoding. - string htmlContent = System.IO.File.ReadAllText(sourcePath, System.Text.Encoding.GetEncoding("windows-1252")); - - // Load the HTML document from a memory stream. - byte[] bytes = System.Text.Encoding.UTF8.GetBytes(htmlContent); - using (var inputStream = new System.IO.MemoryStream(bytes)) - using (var document = new Aspose.Html.HTMLDocument(inputStream, "")) - { - var metaElements = document.GetElementsByTagName("meta"); - foreach (Aspose.Html.Dom.Element meta in metaElements) - { - string charset = meta.GetAttribute("charset"); - if (!string.IsNullOrEmpty(charset)) - { - string actualEncoding = System.Text.Encoding.GetEncoding("windows-1252").WebName; - if (!string.Equals(charset, actualEncoding, System.StringComparison.OrdinalIgnoreCase)) - { - meta.SetAttribute("charset", actualEncoding); - } - } - } - - document.Save(outputPath); - } - - System.Console.WriteLine("Processing completed."); - } - catch (System.Exception ex) - { - System.Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_email_addresses_from_mailto_links_compile_plain_text_list.cs b/html-navigation/extract_email_addresses_from_mailto_links_compile_plain_text_list.cs deleted file mode 100644 index 752e43d..0000000 --- a/html-navigation/extract_email_addresses_from_mailto_links_compile_plain_text_list.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Extract email addresses from mailto links and compile them into a plain‑text list. - -using System; -using System.Collections.Generic; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Create a sample HTML file with mailto links - string htmlPath = "sample.html"; - string htmlContent = "" + - "Alice" + - "Bob" + - "Website" + - ""; - File.WriteAllText(htmlPath, htmlContent); - - // Load the HTML document - var document = new Aspose.Html.HTMLDocument(htmlPath); - - // Select all elements with href starting with "mailto:" - var linkElements = document.QuerySelectorAll("a[href^='mailto:']"); - - var emails = new List(); - - foreach (Aspose.Html.Dom.Element link in linkElements) - { - string href = link.GetAttribute("href"); - if (string.IsNullOrEmpty(href)) - continue; - - const string mailtoPrefix = "mailto:"; - if (href.StartsWith(mailtoPrefix, StringComparison.OrdinalIgnoreCase)) - { - string email = href.Substring(mailtoPrefix.Length); - emails.Add(email); - } - } - - // Output the extracted email addresses - Console.WriteLine("Extracted email addresses:"); - foreach (string email in emails) - { - Console.WriteLine(email); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_embedded_video_source_urls_from_iframe_elements_for_media_cataloging.cs b/html-navigation/extract_embedded_video_source_urls_from_iframe_elements_for_media_cataloging.cs deleted file mode 100644 index 6c1f708..0000000 --- a/html-navigation/extract_embedded_video_source_urls_from_iframe_elements_for_media_cataloging.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Extract embedded video source URLs from iframe elements for the media cataloging. - -namespace Example -{ - class Program - { - static void Main() - { - try - { - string html = ""; - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html); - Aspose.Html.Collections.HTMLCollection iframes = document.GetElementsByTagName("iframe"); - for (int i = 0; i < iframes.Length; i++) - { - Aspose.Html.Dom.Element iframeElement = (Aspose.Html.Dom.Element)iframes[i]; - string src = iframeElement.GetAttribute("src"); - if (string.IsNullOrEmpty(src)) - continue; - Aspose.Html.Url absoluteUrl = new Aspose.Html.Url(src, document.BaseURI); - System.Console.WriteLine(absoluteUrl.ToString()); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_heading_elements_assign_incremental_ids_anchor_linking_document.cs b/html-navigation/extract_heading_elements_assign_incremental_ids_anchor_linking_document.cs deleted file mode 100644 index 146df0c..0000000 --- a/html-navigation/extract_heading_elements_assign_incremental_ids_anchor_linking_document.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Extract all heading elements and assign incremental IDs for anchor linking within the document. - -using System; -using Aspose.Html; -using Aspose.Html.Dom; -using Aspose.Html.Collections; - -class Program -{ - static void Main() - { - try - { - // Create a new HTML document - using (HTMLDocument doc = new HTMLDocument()) - { - // Sample headings - var body = doc.Body; - - var h1 = (HTMLHeadingElement)doc.CreateElement("h1"); - h1.AppendChild(doc.CreateTextNode("First Heading")); - body.AppendChild(h1); - - var h2 = (HTMLHeadingElement)doc.CreateElement("h2"); - h2.AppendChild(doc.CreateTextNode("Second Heading")); - body.AppendChild(h2); - - var h3 = (HTMLHeadingElement)doc.CreateElement("h3"); - h3.AppendChild(doc.CreateTextNode("Third Heading")); - body.AppendChild(h3); - - // Assign incremental IDs to all heading elements - int idCounter = 1; - string[] headingTags = { "h1", "h2", "h3", "h4", "h5", "h6" }; - foreach (var tag in headingTags) - { - HTMLCollection collection = doc.GetElementsByTagName(tag); - for (int i = 0; i < collection.Length; i++) - { - var heading = collection[i] as HTMLHeadingElement; - if (heading != null) - { - string id = "heading" + idCounter++; - heading.SetAttribute("id", id); - } - } - } - - // Create a list of anchor links to the headings - var ul = (HTMLElement)doc.CreateElement("ul"); - foreach (var tag in headingTags) - { - HTMLCollection collection = doc.GetElementsByTagName(tag); - for (int i = 0; i < collection.Length; i++) - { - var heading = collection[i] as HTMLHeadingElement; - if (heading != null) - { - string id = heading.GetAttribute("id"); - var li = (HTMLElement)doc.CreateElement("li"); - var a = (HTMLAnchorElement)doc.CreateElement("a"); - a.SetAttribute("href", "#" + id); - a.AppendChild(doc.CreateTextNode(heading.TextContent)); - li.AppendChild(a); - ul.AppendChild(li); - } - } - } - - // Insert the list at the beginning of the body - var firstChild = body.FirstChild; - if (firstChild != null) - body.InsertBefore(ul, firstChild); - else - body.AppendChild(ul); - - // Save the modified document - string outputPath = "output.html"; - doc.Save(outputPath); - Console.WriteLine("Document saved to " + outputPath); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_hyperlink_href_attributes_from_anchor_tags_write_csv_file.cs b/html-navigation/extract_hyperlink_href_attributes_from_anchor_tags_write_csv_file.cs deleted file mode 100644 index 1f31fa5..0000000 --- a/html-navigation/extract_hyperlink_href_attributes_from_anchor_tags_write_csv_file.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Extract all hyperlink href attributes from anchor tags and write them to a CSV file. - -using System; -using System.IO; -using System.Collections.Generic; - -class Program -{ - static void Main() - { - try - { - // Create a sample HTML file - string htmlPath = "sample.html"; - string htmlContent = "" + - "Example" + - "Test" + - "Empty" + - ""; - File.WriteAllText(htmlPath, htmlContent); - - // Load the HTML document - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath)) - { - Aspose.Html.Collections.HTMLCollection links = document.GetElementsByTagName("a"); - List hrefs = new List(); - - for (int i = 0; i < links.Length; i++) - { - Aspose.Html.Dom.Element link = links[i]; - string href = link.GetAttribute("href"); - if (!string.IsNullOrEmpty(href)) - { - hrefs.Add(href); - } - } - - // Write hrefs to CSV - string csvPath = "links.csv"; - using (StreamWriter writer = new StreamWriter(csvPath)) - { - writer.WriteLine("Href"); - foreach (string href in hrefs) - { - string escaped = href.Replace("\"", "\"\""); - writer.WriteLine($"\"{escaped}\""); - } - } - - Console.WriteLine($"Extracted {hrefs.Count} links to {csvPath}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_link_elements_rel_icon_verify_file_formats_favicon_compliance.cs b/html-navigation/extract_link_elements_rel_icon_verify_file_formats_favicon_compliance.cs deleted file mode 100644 index 2ca1c29..0000000 --- a/html-navigation/extract_link_elements_rel_icon_verify_file_formats_favicon_compliance.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Extract all link elements with rel="icon" and verify their file formats for favicon compliance. - -using System; -using System.Collections.Generic; -using System.IO; - -class Program -{ - static void Main() - { - try - { - // Prepare sample HTML with icon links - string htmlContent = "" + - "" + - "" + - "" + - ""; - string htmlPath = "sample.html"; - File.WriteAllText(htmlPath, htmlContent); - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); - - // Iterate over all link elements and process those with rel=\"icon\" - foreach (Aspose.Html.Dom.Element linkElement in document.Links) - { - string rel = linkElement.GetAttribute("rel"); - if (string.IsNullOrEmpty(rel) || !rel.Equals("icon", StringComparison.OrdinalIgnoreCase)) - continue; - - string href = linkElement.GetAttribute("href"); - if (string.IsNullOrEmpty(href)) - continue; - - // Resolve the URL relative to the document's base URI - Aspose.Html.Url resolvedUrl = new Aspose.Html.Url(href, document.BaseURI); - - // Send a request to fetch the icon resource - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(resolvedUrl); - Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); - - // Determine if the request succeeded - bool isSuccess = response.IsSuccess; - - // Verify file format (favicon compliance) - string urlString = resolvedUrl.ToString(); - string extension = Path.GetExtension(urlString).ToLowerInvariant(); - bool isCompliantFormat = extension == ".ico" || extension == ".png" || extension == ".svg"; - - Console.WriteLine($"Icon href: {urlString}"); - Console.WriteLine($" Request status: {(isSuccess ? "Success" : "Failed")}"); - Console.WriteLine($" File extension: {extension}"); - Console.WriteLine($" Compliant format: {isCompliantFormat}"); - Console.WriteLine(); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_link_elements_rel_preload_list_resource_urls_performance_audit.cs b/html-navigation/extract_link_elements_rel_preload_list_resource_urls_performance_audit.cs deleted file mode 100644 index 2746042..0000000 --- a/html-navigation/extract_link_elements_rel_preload_list_resource_urls_performance_audit.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Extract all link elements with rel="preload" and list their resource URLs for performance audit. - -using System; -using System.Collections.Generic; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; - -class Program -{ - static void Main(string[] args) - { - try - { - string htmlContent = "" + - "" + - "" + - "" + - ""; - - HTMLDocument document = new HTMLDocument(htmlContent); - HTMLCollection linkElements = document.GetElementsByTagName("link"); - - List preloadUrls = new List(); - - for (int i = 0; i < linkElements.Length; i++) - { - Element link = linkElements[i] as Element; - if (link != null) - { - string rel = link.GetAttribute("rel"); - if (string.Equals(rel, "preload", StringComparison.OrdinalIgnoreCase)) - { - string href = link.GetAttribute("href"); - if (!string.IsNullOrEmpty(href)) - { - preloadUrls.Add(href); - } - } - } - } - - Console.WriteLine("Preload resource URLs:"); - foreach (string url in preloadUrls) - { - Console.WriteLine(url); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_meta_description_content_summarize_length_content_quality_checks.cs b/html-navigation/extract_meta_description_content_summarize_length_content_quality_checks.cs deleted file mode 100644 index 6c09398..0000000 --- a/html-navigation/extract_meta_description_content_summarize_length_content_quality_checks.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Extract all meta description content and summarize its length for content quality checks. - -using System; - -class Program -{ - static void Main() - { - try - { - string html = "

Hello World

"; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html)) - { - Aspose.Html.Collections.HTMLCollection metas = document.GetElementsByTagName("meta"); - int totalLength = 0; - for (int i = 0; i < metas.Length; i++) - { - Aspose.Html.HTMLElement meta = metas[i] as Aspose.Html.HTMLElement; - if (meta != null) - { - string name = meta.GetAttribute("name"); - if (!string.IsNullOrEmpty(name) && name.Equals("description", StringComparison.OrdinalIgnoreCase)) - { - string content = meta.GetAttribute("content"); - if (!string.IsNullOrEmpty(content)) - { - totalLength += content.Length; - Console.WriteLine($"Description: \"{content}\" (Length: {content.Length})"); - } - } - } - } - Console.WriteLine($"Total description length: {totalLength}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_open_graph_meta_tags_to_dictionary_for_social_media_integration.cs b/html-navigation/extract_open_graph_meta_tags_to_dictionary_for_social_media_integration.cs deleted file mode 100644 index d1c7ece..0000000 --- a/html-navigation/extract_open_graph_meta_tags_to_dictionary_for_social_media_integration.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Extract Open Graph meta tags and output them as a dictionary for social media integration. - -using System; -using System.Collections.Generic; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; - -class Program -{ - static void Main(string[] args) - { - try - { - string html = @" - - - - - - Test - - -"; - - using (HTMLDocument document = new HTMLDocument(html)) - { - HTMLCollection metaCollection = document.GetElementsByTagName("meta"); - var ogTags = new Dictionary(); - - for (int i = 0; i < metaCollection.Length; i++) - { - Element meta = metaCollection[i] as Element; - if (meta != null) - { - string property = meta.GetAttribute("property"); - if (!string.IsNullOrEmpty(property) && property.StartsWith("og:")) - { - string content = meta.GetAttribute("content"); - if (!string.IsNullOrEmpty(content)) - { - ogTags[property] = content; - } - } - } - } - - foreach (var kvp in ogTags) - { - Console.WriteLine($"{kvp.Key}: {kvp.Value}"); - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_table_data_html_tables_export_each_table_separate_csv_file.cs b/html-navigation/extract_table_data_html_tables_export_each_table_separate_csv_file.cs deleted file mode 100644 index 980376a..0000000 --- a/html-navigation/extract_table_data_html_tables_export_each_table_separate_csv_file.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Extract table data from HTML tables and export each table to a separate CSV file. - -class Program -{ - static void Main() - { - try - { - string html = "" + - "
Header1Header2
Row1Col1Row1Col2
" + - "
AB
CD
" + - ""; - - var document = new Aspose.Html.HTMLDocument(html); - var tables = document.GetElementsByTagName("table"); - int tableIndex = 1; - foreach (var tableNode in tables) - { - if (tableNode is Aspose.Html.HTMLTableElement table) - { - var sb = new System.Text.StringBuilder(); - var rows = table.GetElementsByTagName("tr"); - foreach (var rowNode in rows) - { - if (rowNode is Aspose.Html.HTMLTableRowElement row) - { - var cells = row.Cells; - bool firstCell = true; - foreach (var cell in cells) - { - string cellText = cell.TextContent?.Trim(); - if (cellText != null && cellText.Contains("\"")) - { - cellText = cellText.Replace("\"", "\"\""); - } - if (cellText != null && (cellText.Contains(",") || cellText.Contains("\""))) - { - cellText = $"\"{cellText}\""; - } - if (!firstCell) sb.Append(","); - sb.Append(cellText); - firstCell = false; - } - sb.AppendLine(); - } - } - string fileName = $"table_{tableIndex}.csv"; - System.IO.File.WriteAllText(fileName, sb.ToString()); - System.Console.WriteLine($"Table {tableIndex} saved to {fileName}"); - tableIndex++; - } - } - } - catch (System.Exception ex) - { - System.Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_theme_color_meta_tag_value_for_progressive_web_app_configuration.cs b/html-navigation/extract_theme_color_meta_tag_value_for_progressive_web_app_configuration.cs deleted file mode 100644 index e3908d4..0000000 --- a/html-navigation/extract_theme_color_meta_tag_value_for_progressive_web_app_configuration.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Extract the theme‑color meta tag value for use in progressive web app configuration. - -using System; - -class Program -{ - static void Main() - { - try - { - string inputPath = "sample.html"; - string htmlContent = ""; - System.IO.File.WriteAllText(inputPath, htmlContent); - - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - Aspose.Html.Collections.NodeList metaElements = document.QuerySelectorAll("meta[name='theme-color']"); - - bool found = false; - foreach (Aspose.Html.HTMLElement element in metaElements) - { - string themeColor = element.GetAttribute("content"); - Console.WriteLine("Theme color meta tag value: " + themeColor); - found = true; - break; - } - - if (!found) - { - Console.WriteLine("Theme color meta tag not found."); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/extract_value_robots_meta_tag_determine_indexing_directives.cs b/html-navigation/extract_value_robots_meta_tag_determine_indexing_directives.cs deleted file mode 100644 index 25f675c..0000000 --- a/html-navigation/extract_value_robots_meta_tag_determine_indexing_directives.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Extract the value of the robots meta tag to determine indexing directives. - -class Program -{ - static void Main() - { - try - { - string html = "Test

Hello

"; - Aspose.Html.HTMLDocument doc = new Aspose.Html.HTMLDocument(html); - Aspose.Html.Dom.XPath.IXPathResult result = doc.Evaluate("//meta[@name='robots']", doc, doc.CreateNSResolver(doc), Aspose.Html.Dom.XPath.XPathResultType.Any, null); - Aspose.Html.Dom.Node node = result.IterateNext(); - if (node != null) - { - Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)node; - string content = element.GetAttribute("content"); - System.Console.WriteLine("Robots meta content: " + content); - } - else - { - System.Console.WriteLine("Robots meta tag not found."); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/find-all-form-elements-list-their-input-field-names-and-default-values-for-analysis.cs b/html-navigation/find-all-form-elements-list-their-input-field-names-and-default-values-for-analysis.cs new file mode 100644 index 0000000..0381f93 --- /dev/null +++ b/html-navigation/find-all-form-elements-list-their-input-field-names-and-default-values-for-analysis.cs @@ -0,0 +1,48 @@ +// Find all form elements, list their input field names and default values for analysis. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = @"
"; + + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + var forms = document.QuerySelectorAll("form"); + + foreach (Aspose.Html.HTMLElement form in forms) + { + var fields = form.QuerySelectorAll("input, select, textarea"); + foreach (Aspose.Html.HTMLElement field in fields) + { + string name = field.GetAttribute("name"); + string value = field.GetAttribute("value"); + string tag = field.TagName.ToLowerInvariant(); + + if (tag == "select") + { + var selectedOption = field.QuerySelector("option[selected]"); + if (selectedOption != null) + { + value = selectedOption.GetAttribute("value"); + } + } + else if (tag == "textarea") + { + value = field.TextContent; + } + + Console.WriteLine($"Field Name: {name}, Default Value: {value}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/find-element-by-unique-id-modify-inner-text-new-value.cs b/html-navigation/find-element-by-unique-id-modify-inner-text-new-value.cs new file mode 100644 index 0000000..7e2fe65 --- /dev/null +++ b/html-navigation/find-element-by-unique-id-modify-inner-text-new-value.cs @@ -0,0 +1,27 @@ +// Find an element by its unique ID attribute and modify its inner text to a new value. + +using System; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "

Old text

"; + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + var elements = document.QuerySelectorAll("#myId"); + foreach (Aspose.Html.HTMLElement element in elements) + { + element.InnerHTML = "New text"; + break; + } + document.Save("output.html"); + Console.WriteLine("Document saved successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/find_phone_number_patterns_within_text_nodes_output_for_contact_information_extraction.cs b/html-navigation/find-phone-number-patterns-within-text-nodes-output-for-contact-information-extraction.cs similarity index 53% rename from html-navigation/find_phone_number_patterns_within_text_nodes_output_for_contact_information_extraction.cs rename to html-navigation/find-phone-number-patterns-within-text-nodes-output-for-contact-information-extraction.cs index b645d5e..0bb5526 100644 --- a/html-navigation/find_phone_number_patterns_within_text_nodes_output_for_contact_information_extraction.cs +++ b/html-navigation/find-phone-number-patterns-within-text-nodes-output-for-contact-information-extraction.cs @@ -12,19 +12,29 @@ static void Main() { try { - string htmlContent = "Contact: John Doe, Phone: +1 (555) 123-4567. Another: 555-987-6543."; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "")) + string html = "

Contact us at +1 (555) 123-4567 or 555-987-6543.

Another number: 123.456.7890
"; + + using (HTMLDocument document = new HTMLDocument(html, "about:blank")) { - IXPathResult result = document.Evaluate("//text()", document, null, Aspose.Html.Dom.XPath.XPathResultType.Any, null); + IXPathResult result = document.Evaluate("//text()", document, null, XPathResultType.Any, null); + Regex phoneRegex = new Regex(@"\+?\d[\d\-\.\(\) ]{7,}\d"); + bool anyFound = false; + for (Node node; (node = result.IterateNext()) != null;) { string text = node.TextContent; - Regex regex = new Regex(@"\+?\d[\d\-\s\(\)]{7,}\d"); - foreach (Match match in regex.Matches(text)) + MatchCollection matches = phoneRegex.Matches(text); + foreach (Match match in matches) { Console.WriteLine("Phone number found: " + match.Value); + anyFound = true; } } + + if (!anyFound) + { + Console.WriteLine("No phone numbers found."); + } } } catch (Exception ex) diff --git a/html-navigation/find_all_form_elements_list_input_field_names_and_default_values_analysis.cs b/html-navigation/find_all_form_elements_list_input_field_names_and_default_values_analysis.cs deleted file mode 100644 index b20edf9..0000000 --- a/html-navigation/find_all_form_elements_list_input_field_names_and_default_values_analysis.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Find all form elements, list their input field names and default values for analysis. - -using System; -using System.IO; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; - -class Program -{ - static void Main() - { - try - { - // Create a sample HTML file with forms - string htmlContent = @" - - -Sample Form - -
- - - -
-
- - -
- -"; - string inputPath = "sample.html"; - File.WriteAllText(inputPath, htmlContent); - - // Load the HTML document - HTMLDocument document = new HTMLDocument(inputPath); - - // Get all form elements - HTMLCollection forms = document.GetElementsByTagName("form"); - for (int i = 0; i < forms.Length; i++) - { - Element form = (Element)forms[i]; - Console.WriteLine($"Form #{i + 1}:"); - - // Get all input elements within the form - HTMLCollection inputs = form.GetElementsByTagName("input"); - for (int j = 0; j < inputs.Length; j++) - { - Element input = (Element)inputs[j]; - string name = input.GetAttribute("name"); - string value = input.GetAttribute("value"); - Console.WriteLine($" Input Name: {name ?? "(no name)"}; Default Value: {value ?? "(no value)"}"); - } - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/find_element_by_unique_id_attribute_and_modify_inner_text_to_new_value.cs b/html-navigation/find_element_by_unique_id_attribute_and_modify_inner_text_to_new_value.cs deleted file mode 100644 index d6c90fb..0000000 --- a/html-navigation/find_element_by_unique_id_attribute_and_modify_inner_text_to_new_value.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Find an element by its unique ID attribute and modify its inner text to a new value. - -class Program -{ - static void Main() - { - try - { - string htmlContent = "Sample

Old text

"; - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument("", htmlContent); - Aspose.Html.Collections.NodeList elements = document.QuerySelectorAll("#myId"); - foreach (Aspose.Html.HTMLElement element in elements) - { - element.InnerHTML = "New text"; - } - string outputPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "output.html"); - document.Save(outputPath); - System.Console.WriteLine("Document saved to: " + outputPath); - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/generate_json_sitemap_traversing_all_anchor_elements_recording_absolute_urls.cs b/html-navigation/generate-json-sitemap-traversing-all-anchor-elements-recording-absolute-urls.cs similarity index 54% rename from html-navigation/generate_json_sitemap_traversing_all_anchor_elements_recording_absolute_urls.cs rename to html-navigation/generate-json-sitemap-traversing-all-anchor-elements-recording-absolute-urls.cs index d7147fd..a0996c9 100644 --- a/html-navigation/generate_json_sitemap_traversing_all_anchor_elements_recording_absolute_urls.cs +++ b/html-navigation/generate-json-sitemap-traversing-all-anchor-elements-recording-absolute-urls.cs @@ -14,39 +14,21 @@ static void Main() { try { - // Sample HTML content - string htmlContent = @" - - - - Page 1 - External Page - Relative Page - - "; - - // Load HTML document - using (HTMLDocument document = new HTMLDocument(htmlContent)) + string html = "Page 1Page 2"; + using (HTMLDocument document = new HTMLDocument(html, "http://localhost/")) { - // Get all anchor elements HTMLCollection anchors = document.GetElementsByTagName("a"); - List absoluteUrls = new List(); - + List urlList = new List(); for (int i = 0; i < anchors.Length; i++) { Element link = anchors[i] as Element; if (link == null) continue; - string href = link.GetAttribute("href"); if (string.IsNullOrEmpty(href)) continue; - - // Resolve absolute URL Url absoluteUrl = new Url(href, document.BaseURI); - absoluteUrls.Add(absoluteUrl.ToString()); + urlList.Add(absoluteUrl.ToString()); } - - // Serialize to JSON - string json = JsonSerializer.Serialize(absoluteUrls, new JsonSerializerOptions { WriteIndented = true }); + string json = JsonSerializer.Serialize(urlList, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(json); } } diff --git a/html-navigation/generate-navigation-sidebar-html-snippet-based-on-extracted-heading-hierarchy-site.cs b/html-navigation/generate-navigation-sidebar-html-snippet-based-on-extracted-heading-hierarchy-site.cs new file mode 100644 index 0000000..d2482a6 --- /dev/null +++ b/html-navigation/generate-navigation-sidebar-html-snippet-based-on-extracted-heading-hierarchy-site.cs @@ -0,0 +1,96 @@ +// Generate a navigation sidebar HTML snippet based on extracted heading hierarchy for the site. + +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Net; + +class Program +{ + class OutlineNode + { + public string Text { get; set; } + public int Level { get; set; } + public List Children { get; set; } = new List(); + } + + static void Main() + { + try + { + string inputFolder = "InputHtml"; + string outputFolder = "OutputSidebar"; + + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); + + foreach (string htmlPath in Directory.GetFiles(inputFolder, "*.html")) + { + // Load HTML document + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath); + + // Select all heading elements + var headings = document.QuerySelectorAll("h1, h2, h3, h4, h5, h6"); + + // Build hierarchical outline + var root = new List(); + var stack = new Stack(); + + for (int i = 0; i < headings.Length; i++) + { + Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)headings[i]; + string tag = element.TagName.ToLower(); + int level = int.Parse(tag.Substring(1)); + + var node = new OutlineNode + { + Text = element.TextContent.Trim(), + Level = level + }; + + while (stack.Count > 0 && stack.Peek().Level >= level) + stack.Pop(); + + if (stack.Count == 0) + root.Add(node); + else + stack.Peek().Children.Add(node); + + stack.Push(node); + } + + // Generate navigation sidebar HTML + StringBuilder sb = new StringBuilder(); + sb.AppendLine(""); + + string outputPath = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(htmlPath) + "_sidebar.html"); + File.WriteAllText(outputPath, sb.ToString()); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + + static void GenerateList(List nodes, StringBuilder sb) + { + if (nodes == null || nodes.Count == 0) + return; + + sb.AppendLine("
    "); + foreach (var node in nodes) + { + sb.Append("
  • ").Append(WebUtility.HtmlEncode(node.Text)); + if (node.Children != null && node.Children.Count > 0) + { + GenerateList(node.Children, sb); + } + sb.AppendLine("
  • "); + } + sb.AppendLine("
"); + } +} \ No newline at end of file diff --git a/html-navigation/generate-report-summarizing-number-of-each-html-element-type-present-in-document.cs b/html-navigation/generate-report-summarizing-number-of-each-html-element-type-present-in-document.cs new file mode 100644 index 0000000..097957e --- /dev/null +++ b/html-navigation/generate-report-summarizing-number-of-each-html-element-type-present-in-document.cs @@ -0,0 +1,49 @@ +// Generate a report summarizing the number of each HTML element type present in the document. + +using System; +using System.Collections.Generic; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; + +class Program +{ + static void Main(string[] args) + { + try + { + string htmlContent = "Sample

Paragraph

Link
  • Item1
  • Item2
"; + using (HTMLDocument document = new HTMLDocument(htmlContent, "about:blank")) + { + HTMLCollection allElements = document.GetElementsByTagName("*"); + var elementCounts = new Dictionary(StringComparer.OrdinalIgnoreCase); + + for (int i = 0; i < allElements.Length; i++) + { + Element element = allElements[i] as Element; + if (element == null) + continue; + + string tagName = element.NodeName; + if (string.IsNullOrEmpty(tagName)) + continue; + + if (elementCounts.ContainsKey(tagName)) + elementCounts[tagName]++; + else + elementCounts[tagName] = 1; + } + + Console.WriteLine("HTML Element Summary:"); + foreach (var kvp in elementCounts) + { + Console.WriteLine($"{kvp.Key}: {kvp.Value}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/generate-site-map-xml-file-by-traversing-all-internal-links-discovered-in-html-document.cs b/html-navigation/generate-site-map-xml-file-by-traversing-all-internal-links-discovered-in-html-document.cs new file mode 100644 index 0000000..2b221b9 --- /dev/null +++ b/html-navigation/generate-site-map-xml-file-by-traversing-all-internal-links-discovered-in-html-document.cs @@ -0,0 +1,74 @@ +// Generate a site map XML file by traversing all internal links discovered in the HTML document. + +using System; +using System.IO; +using System.Collections.Generic; +using System.Xml; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Dom.XPath; + +class Program +{ + static void Main(string[] args) + { + try + { + // Sample HTML content + string htmlContent = "" + + "Page 1" + + "External" + + "Page 2" + + "Section" + + ""; + + // Load HTML document from string + HTMLDocument doc = new HTMLDocument(htmlContent, "about:blank"); + + // Evaluate XPath to get all anchor elements with href attribute + IXPathResult result = doc.Evaluate("//a[@href]", doc, doc.CreateNSResolver(doc), XPathResultType.Any, null); + + Node node; + HashSet links = new HashSet(); + + while ((node = result.IterateNext()) != null) + { + HTMLAnchorElement anchor = node as HTMLAnchorElement; + if (anchor != null) + { + string href = anchor.Href; + if (!string.IsNullOrEmpty(href) && + !(href.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + href.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) + { + links.Add(href); + } + } + } + + // Generate sitemap.xml + XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; + using (XmlWriter writer = XmlWriter.Create("sitemap.xml", settings)) + { + writer.WriteStartDocument(); + writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); + + foreach (string loc in links) + { + writer.WriteStartElement("url"); + writer.WriteElementString("loc", loc); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); // urlset + writer.WriteEndDocument(); + } + + Console.WriteLine("Sitemap generated: sitemap.xml"); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/generate_report_summarizing_number_of_each_html_element_type_in_document.cs b/html-navigation/generate_report_summarizing_number_of_each_html_element_type_in_document.cs deleted file mode 100644 index da1797b..0000000 --- a/html-navigation/generate_report_summarizing_number_of_each_html_element_type_in_document.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Generate a report summarizing the number of each HTML element type present in the document. - -using System; -using System.Collections.Generic; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; - -class Program -{ - static void Main(string[] args) - { - try - { - string htmlContent = "Sample

Paragraph

Link
  • Item1
  • Item2
"; - var document = new Aspose.Html.HTMLDocument(htmlContent); - - HTMLCollection allElements = document.GetElementsByTagName("*"); - var tagCounts = new Dictionary(StringComparer.OrdinalIgnoreCase); - - for (int i = 0; i < allElements.Length; i++) - { - var element = allElements[i] as Aspose.Html.Dom.Element; - if (element != null) - { - string tagName = element.NodeName.ToLowerInvariant(); - if (tagCounts.ContainsKey(tagName)) - tagCounts[tagName]++; - else - tagCounts[tagName] = 1; - } - } - - Console.WriteLine("HTML Element Summary:"); - foreach (var kvp in tagCounts) - { - Console.WriteLine($"{kvp.Key}: {kvp.Value}"); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/identify_and_list_external_script_source_urls_for_dependency_analysis_in_document.cs b/html-navigation/identify-and-list-external-script-source-urls-for-dependency-analysis-in-document.cs similarity index 79% rename from html-navigation/identify_and_list_external_script_source_urls_for_dependency_analysis_in_document.cs rename to html-navigation/identify-and-list-external-script-source-urls-for-dependency-analysis-in-document.cs index f97a53d..8b40e7e 100644 --- a/html-navigation/identify_and_list_external_script_source_urls_for_dependency_analysis_in_document.cs +++ b/html-navigation/identify-and-list-external-script-source-urls-for-dependency-analysis-in-document.cs @@ -9,27 +9,29 @@ static void Main() try { string inputPath = "sample.html"; + if (!System.IO.File.Exists(inputPath)) { - string sampleHtml = ""; + string sampleHtml = ""; System.IO.File.WriteAllText(inputPath, sampleHtml); } Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); Aspose.Html.Collections.HTMLCollection scriptElements = document.GetElementsByTagName("script"); + for (int i = 0; i < scriptElements.Length; i++) { Aspose.Html.Dom.Element scriptElement = (Aspose.Html.Dom.Element)scriptElements[i]; string src = scriptElement.GetAttribute("src"); if (!string.IsNullOrEmpty(src)) { - System.Console.WriteLine(src); + Console.WriteLine(src); } } } - catch (System.Exception ex) + catch (Exception ex) { - System.Console.WriteLine(ex.Message); + Console.WriteLine(ex.Message); } } } \ No newline at end of file diff --git a/html-navigation/identify-extract-all-data-attribute-values-custom-javascript-data-binding-document.cs b/html-navigation/identify-extract-all-data-attribute-values-custom-javascript-data-binding-document.cs new file mode 100644 index 0000000..1f61ea6 --- /dev/null +++ b/html-navigation/identify-extract-all-data-attribute-values-custom-javascript-data-binding-document.cs @@ -0,0 +1,41 @@ +// Identify and extract all data‑attribute values for custom JavaScript data binding in the document. + +class Program +{ + static void Main() + { + try + { + string inputPath = "sample.html"; + if (!System.IO.File.Exists(inputPath)) + { + System.IO.File.WriteAllText(inputPath, + "
Hello
"); + } + + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); + + var elements = document.QuerySelectorAll("*"); + for (int i = 0; i < elements.Length; i++) + { + Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)elements[i]; + var attributeNames = element.GetAttributeNames(); + foreach (var name in attributeNames) + { + if (name.StartsWith("data-")) + { + string value = element.GetAttribute(name); + if (!string.IsNullOrEmpty(value)) + { + System.Console.WriteLine($"{name} = {value}"); + } + } + } + } + } + catch (System.Exception ex) + { + System.Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/identify-extract-microdata-items-itemtype-attributes-convert-to-structured-list.cs b/html-navigation/identify-extract-microdata-items-itemtype-attributes-convert-to-structured-list.cs new file mode 100644 index 0000000..1f77284 --- /dev/null +++ b/html-navigation/identify-extract-microdata-items-itemtype-attributes-convert-to-structured-list.cs @@ -0,0 +1,85 @@ +// Identify and extract microdata items using itemtype attributes and convert them to a structured list. + +using System; +using System.Collections.Generic; +using System.Text.Json; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; + +class Program +{ + static void Main() + { + try + { + // Sample HTML with microdata + string htmlContent = "" + + "
" + + "John Doe" + + "Software Engineer" + + "
" + + "
" + + "Acme Corp" + + "https://www.acme.com" + + "
" + + ""; + + // Load HTML document from string (use two‑argument constructor) + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + // Find all elements that define a microdata item (have itemtype attribute) + Aspose.Html.Collections.NodeList itemElements = document.QuerySelectorAll("[itemtype]"); + + var result = new List(); + + for (int i = 0; i < itemElements.Length; i++) + { + Aspose.Html.Dom.Element itemElement = (Aspose.Html.Dom.Element)itemElements[i]; + string itemType = itemElement.GetAttribute("itemtype") ?? string.Empty; + + // Find all descendant elements with itemprop attribute + Aspose.Html.Collections.NodeList propElements = itemElement.QuerySelectorAll("[itemprop]"); + + var properties = new Dictionary(StringComparer.OrdinalIgnoreCase); + + for (int j = 0; j < propElements.Length; j++) + { + Aspose.Html.Dom.Element propElement = (Aspose.Html.Dom.Element)propElements[j]; + string propName = propElement.GetAttribute("itemprop") ?? string.Empty; + string propValue = propElement.TextContent?.Trim() ?? string.Empty; + + if (!string.IsNullOrEmpty(propName)) + { + properties[propName] = propValue; + } + } + + var microdataItem = new MicrodataItem + { + ItemType = itemType, + Properties = properties + }; + + result.Add(microdataItem); + } + + // Serialize result to JSON and output + var jsonOptions = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; + string json = System.Text.Json.JsonSerializer.Serialize(result, jsonOptions); + Console.WriteLine(json); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + + // Simple model to hold extracted microdata + class MicrodataItem + { + public string ItemType { get; set; } + public Dictionary Properties { get; set; } + } +} \ No newline at end of file diff --git a/html-navigation/identify-inline-style-definitions-move-to-external-stylesheet-cleaner-markup.cs b/html-navigation/identify-inline-style-definitions-move-to-external-stylesheet-cleaner-markup.cs new file mode 100644 index 0000000..09a42fd --- /dev/null +++ b/html-navigation/identify-inline-style-definitions-move-to-external-stylesheet-cleaner-markup.cs @@ -0,0 +1,67 @@ +// Identify inline style definitions and move them to an external stylesheet for cleaner markup. + +using System; +using System.IO; +using System.Linq; +using System.Text; + +class Program +{ + static void Main() + { + try + { + // Sample HTML with inline styles + string htmlContent = "" + + "

Hello World

" + + "
Sample Box
" + + ""; + + // Load HTML document from string using two‑argument constructor (content, baseUri) + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Find all elements that have a style attribute + Aspose.Html.Collections.NodeList elementsWithStyle = document.QuerySelectorAll("[style]"); + + StringBuilder cssBuilder = new StringBuilder(); + int index = 0; + + foreach (Aspose.Html.Dom.Element element in elementsWithStyle) + { + string inlineStyle = element.GetAttribute("style"); + if (string.IsNullOrEmpty(inlineStyle)) + continue; + + string className = $"inlineStyle{index}"; + string existingClass = element.GetAttribute("class"); + string newClass = string.IsNullOrEmpty(existingClass) ? className : $"{existingClass} {className}"; + element.SetAttribute("class", newClass); + element.RemoveAttribute("style"); + + cssBuilder.AppendLine($".{className} {{{inlineStyle}}}"); + index++; + } + + // Create a - - -

Hello World!

-

This is a paragraph with extra spaces.

-
    -
  • Item 1
  • -
  • Item 2
  • -
- -"; - - // Load HTML into Aspose.HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent); - - // Get the original outer HTML - string originalHtml = document.DocumentElement.OuterHTML; - - // Collapse whitespace - string minified = Regex.Replace(originalHtml, @"\s+", " "); - - // Remove optional closing tags (common ones) - string[] optionalClosingTags = new string[] - { - "

", "", "", "", "", "", "", - "", "", "", "", "", "" - }; - foreach (string tag in optionalClosingTags) - { - minified = minified.Replace(tag, string.Empty); - } - - // Trim leading/trailing spaces - minified = minified.Trim(); - - Console.WriteLine("Original HTML:"); - Console.WriteLine(originalHtml); - Console.WriteLine(); - Console.WriteLine("Minified HTML:"); - Console.WriteLine(minified); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/move-script-element-from-head-to-body-end-improve-page-loading.cs b/html-navigation/move-script-element-from-head-to-body-end-improve-page-loading.cs new file mode 100644 index 0000000..4606c65 --- /dev/null +++ b/html-navigation/move-script-element-from-head-to-body-end-improve-page-loading.cs @@ -0,0 +1,53 @@ +// Move a script element from the head to the end of the body to improve page loading. + +using System; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + try + { + string inputPath = "sample.html"; + string outputPath = "output.html"; + + if (!File.Exists(inputPath)) + { + string sampleHtml = "Test

Hello

"; + File.WriteAllText(inputPath, sampleHtml); + } + + Aspose.Html.Configuration config = new Aspose.Html.Configuration(); + config.Security |= Aspose.Html.Sandbox.Scripts; + + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath, config); + + Aspose.Html.HTMLElement head = document.QuerySelector("head") as Aspose.Html.HTMLElement; + Aspose.Html.HTMLElement body = document.QuerySelector("body") as Aspose.Html.HTMLElement; + + if (head != null && body != null) + { + Aspose.Html.Collections.HTMLCollection scriptCollection = head.GetElementsByTagName("script"); + List scripts = new List(); + for (int i = 0; i < scriptCollection.Length; i++) + { + scripts.Add((Aspose.Html.Dom.Element)scriptCollection[i]); + } + + foreach (var script in scripts) + { + head.RemoveChild(script); + body.AppendChild(script); + } + } + + document.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/move_script_element_from_head_to_body_end_improve_page_loading.cs b/html-navigation/move_script_element_from_head_to_body_end_improve_page_loading.cs deleted file mode 100644 index 38bf427..0000000 --- a/html-navigation/move_script_element_from_head_to_body_end_improve_page_loading.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Move a script element from the head to the end of the body to improve page loading. - -using System; -using System.IO; -using System.Linq; -using Aspose.Html; -using Aspose.Html.Dom; -using Aspose.Html.Collections; - -class Program -{ - static void Main() - { - try - { - // Input and output file paths - string inputPath = "input.html"; - string outputPath = "output.html"; - - // Create a minimal sample input file if it does not exist - if (!File.Exists(inputPath)) - { - string sampleHtml = "

Hello World

"; - File.WriteAllText(inputPath, sampleHtml); - } - - // Load the HTML document - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - - // Get head and body elements - Aspose.Html.HTMLElement head = (Aspose.Html.HTMLElement)Enumerable.First(document.GetElementsByTagName("head")); - Aspose.Html.HTMLElement body = (Aspose.Html.HTMLElement)Enumerable.First(document.GetElementsByTagName("body")); - - // Get all script elements - HTMLCollection scriptElements = document.GetElementsByTagName("script"); - - // Move script elements from head to the end of body - for (int i = 0; i < scriptElements.Length; i++) - { - Aspose.Html.Dom.Element scriptElement = (Aspose.Html.Dom.Element)scriptElements[i]; - if (scriptElement.ParentNode == head) - { - head.RemoveChild(scriptElement); - body.AppendChild(scriptElement); - } - } - - // Save the modified document - document.Save(outputPath); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/enable_case_sensitive_element_name_matching_xml_like_html_parsing_specific_documents.cs b/html-navigation/parse-html-string-case-insensitive-tag-handling-preserve-original-whitespace-formatting.cs similarity index 57% rename from html-navigation/enable_case_sensitive_element_name_matching_xml_like_html_parsing_specific_documents.cs rename to html-navigation/parse-html-string-case-insensitive-tag-handling-preserve-original-whitespace-formatting.cs index 83f95f3..14b5d41 100644 --- a/html-navigation/enable_case_sensitive_element_name_matching_xml_like_html_parsing_specific_documents.cs +++ b/html-navigation/parse-html-string-case-insensitive-tag-handling-preserve-original-whitespace-formatting.cs @@ -1,4 +1,4 @@ -// Enable case‑sensitive element name matching for XML‑like HTML parsing scenarios when processing specific documents. +// Parse an HTML string with case‑insensitive tag handling and preserve original whitespace formatting. using System; @@ -8,21 +8,23 @@ static void Main() { try { - string htmlContent = "Value"; + string htmlContent = "

Test

"; + string baseUri = "about:blank"; - // Create a base URL required by the HTMLDocument constructor that accepts HTML string. - Aspose.Html.Url baseUrl = new Aspose.Html.Url("about:blank"); + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, baseUri); - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, baseUrl); - - Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("Item"); + Aspose.Html.Collections.HTMLCollection elements = document.GetElementsByTagName("div"); for (int i = 0; i < elements.Length; i++) { Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)elements[i]; System.Console.WriteLine(element.TagName); } + + string outerHtml = document.DocumentElement.OuterHTML; + System.Console.WriteLine("OuterHTML:"); + System.Console.WriteLine(outerHtml); } - catch (Exception ex) + catch (System.Exception ex) { System.Console.WriteLine("Error: " + ex.Message); } diff --git a/html-navigation/parse_html_string_case_insensitive_tag_handling_preserve_original_whitespace_formatting.cs b/html-navigation/parse_html_string_case_insensitive_tag_handling_preserve_original_whitespace_formatting.cs deleted file mode 100644 index 737481f..0000000 --- a/html-navigation/parse_html_string_case_insensitive_tag_handling_preserve_original_whitespace_formatting.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Parse an HTML string with case‑insensitive tag handling and preserve original whitespace formatting. - -using System; - -class Program -{ - static void Main() - { - try - { - string htmlContent = "

Sample

"; - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, ""); - string output = document.DocumentElement.OuterHTML; - Console.WriteLine(output); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/html-navigation/pretty-print-html-indentation-two-spaces-per-nesting-level-readability.cs b/html-navigation/pretty-print-html-indentation-two-spaces-per-nesting-level-readability.cs new file mode 100644 index 0000000..00b98a2 --- /dev/null +++ b/html-navigation/pretty-print-html-indentation-two-spaces-per-nesting-level-readability.cs @@ -0,0 +1,84 @@ +// Pretty‑print the HTML with indentation of two spaces per nesting level for readability. + +using System; +using System.Text; +using System.Text.RegularExpressions; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content + string htmlContent = "Sample

Hello World

This is a paragraph.

"; + + // Load HTML document using two‑argument constructor (content, baseUri) + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank")) + { + // Get the outer HTML of the document + string rawHtml = document.DocumentElement.OuterHTML; + + // Pretty‑print with two‑space indentation + string formattedHtml = PrettyPrintHtml(rawHtml); + + // Output the formatted HTML + Console.WriteLine(formattedHtml); + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + static string PrettyPrintHtml(string html) + { + var sb = new StringBuilder(); + int indent = 0; + string[] tokens = Regex.Split(html, "(<[^>]+>)"); + + foreach (string token in tokens) + { + if (string.IsNullOrWhiteSpace(token)) + continue; + + if (token.StartsWith("<")) + { + if (token.StartsWith("")) + { + sb.AppendLine(); + sb.Append(new string(' ', indent * 2)); + sb.Append(token); + } + else + { + sb.AppendLine(); + sb.Append(new string(' ', indent * 2)); + sb.Append(token); + indent++; + } + } + else + { + string text = token.Trim(); + if (!string.IsNullOrEmpty(text)) + { + sb.AppendLine(); + sb.Append(new string(' ', indent * 2)); + sb.Append(text); + } + } + } + + return sb.ToString().Trim(); + } +} \ No newline at end of file diff --git a/html-navigation/pretty_print_html_two_space_indentation_per_nesting_level_readability.cs b/html-navigation/pretty_print_html_two_space_indentation_per_nesting_level_readability.cs deleted file mode 100644 index 4a27398..0000000 --- a/html-navigation/pretty_print_html_two_space_indentation_per_nesting_level_readability.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Pretty‑print the HTML with indentation of two spaces per nesting level for readability. - -using System; -using System.Text; -using Aspose.Html; - -class Program -{ - static void Main() - { - try - { - // Sample HTML content - string htmlContent = "Sample

Hello

World

"; - - // Load HTML into document - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "")) - { - // Get raw outer HTML - string rawHtml = document.DocumentElement.OuterHTML; - - // Pretty‑print with two‑space indentation - string prettyHtml = PrettyPrintHtml(rawHtml, 2); - - // Output result - Console.WriteLine(prettyHtml); - } - } - catch (Exception ex) - { - Console.Error.WriteLine($"Error: {ex.Message}"); - } - } - - static string PrettyPrintHtml(string html, int indentSize) - { - var sb = new StringBuilder(); - int indent = 0; - - for (int i = 0; i < html.Length; i++) - { - if (html[i] == '<') - { - bool isClosingTag = i + 1 < html.Length && html[i + 1] == '/'; - if (isClosingTag) - indent = Math.Max(indent - 1, 0); - - sb.Append('\n'); - sb.Append(new string(' ', indent * indentSize)); - - // Append the whole tag - while (i < html.Length && html[i] != '>') - { - sb.Append(html[i]); - i++; - } - if (i < html.Length) - sb.Append('>'); - - bool isSelfClosing = i - 1 >= 0 && html[i - 1] == '/'; - if (!isClosingTag && !isSelfClosing) - indent++; - } - else - { - sb.Append(html[i]); - } - } - - return sb.ToString().TrimStart('\n'); - } -} \ No newline at end of file diff --git a/html-navigation/remove_all_comment_nodes_from_dom_to_produce_clean_html_output.cs b/html-navigation/remove-all-comment-nodes-from-dom-produce-clean-html-output.cs similarity index 81% rename from html-navigation/remove_all_comment_nodes_from_dom_to_produce_clean_html_output.cs rename to html-navigation/remove-all-comment-nodes-from-dom-produce-clean-html-output.cs index 5bc3db9..79059d5 100644 --- a/html-navigation/remove_all_comment_nodes_from_dom_to_produce_clean_html_output.cs +++ b/html-navigation/remove-all-comment-nodes-from-dom-produce-clean-html-output.cs @@ -7,7 +7,7 @@ class Program { - static void Main() + static void Main(string[] args) { try { @@ -16,12 +16,14 @@ static void Main() if (!File.Exists(inputPath)) { - File.WriteAllText(inputPath, - "Test

Hello

"); + string sampleHtml = "Sample

Hello World

"; + File.WriteAllText(inputPath, sampleHtml); } Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); + RemoveComments(document.DocumentElement); + document.Save(outputPath); Console.WriteLine("Clean HTML saved to " + outputPath); @@ -38,6 +40,7 @@ static void RemoveComments(Aspose.Html.Dom.Node node) while (child != null) { var next = child.NextSibling; + if (child.NodeName == "#comment") { node.RemoveChild(child); @@ -46,6 +49,7 @@ static void RemoveComments(Aspose.Html.Dom.Node node) { RemoveComments(child); } + child = next; } } diff --git a/html-navigation/remove-all-deprecated-center-tags-replace-with-css-text-align-styling.cs b/html-navigation/remove-all-deprecated-center-tags-replace-with-css-text-align-styling.cs new file mode 100644 index 0000000..613df75 --- /dev/null +++ b/html-navigation/remove-all-deprecated-center-tags-replace-with-css-text-align-styling.cs @@ -0,0 +1,57 @@ +// Remove all deprecated
tags and replace them with CSS text‑align styling. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Dom; +using Aspose.Html.Collections; + +class Program +{ + static void Main() + { + try + { + // Sample HTML containing deprecated
tags + string htmlContent = "

Welcome

Some text.

Another centered text.
"; + + // Load HTML from string using a dummy base URI + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Get all
elements + Aspose.Html.Collections.HTMLCollection centers = document.GetElementsByTagName("center"); + + // Iterate backwards to safely replace nodes + for (int i = centers.Length - 1; i >= 0; i--) + { + Aspose.Html.Dom.Element center = (Aspose.Html.Dom.Element)centers[i]; + + // Create a
element with CSS text-align styling + Aspose.Html.Dom.Element div = document.CreateElement("div"); + div.SetAttribute("style", "text-align:center;"); + + // Move all child nodes from
to the new
+ while (center.FirstChild != null) + { + Aspose.Html.Dom.Node child = center.FirstChild; + center.RemoveChild(child); + div.AppendChild(child); + } + + // Replace the
element with the new
+ Aspose.Html.Dom.Node parent = center.ParentNode; + parent.ReplaceChild(div, center); + } + + // Save the modified document + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.html"); + document.Save(outputPath); + + System.Console.WriteLine("Processing completed. Output saved to: " + outputPath); + } + catch (Exception ex) + { + System.Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/remove_empty_paragraph_tags_containing_only_whitespace_characters_in_document.cs b/html-navigation/remove-all-empty-paragraph-tags-containing-only-whitespace-characters-document.cs similarity index 53% rename from html-navigation/remove_empty_paragraph_tags_containing_only_whitespace_characters_in_document.cs rename to html-navigation/remove-all-empty-paragraph-tags-containing-only-whitespace-characters-document.cs index cce6035..f6fce6e 100644 --- a/html-navigation/remove_empty_paragraph_tags_containing_only_whitespace_characters_in_document.cs +++ b/html-navigation/remove-all-empty-paragraph-tags-containing-only-whitespace-characters-document.cs @@ -1,9 +1,6 @@ // Remove all empty paragraph tags that contain only whitespace characters in the document. using System; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; class Program { @@ -12,10 +9,10 @@ static void Main(string[] args) try { // Sample HTML content with empty paragraphs - string htmlContent = "

Hello World

\n\t

"; + string htmlContent = "

Text

\n\t

"; - // Load document from string - Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, ""); + // Load document from inline HTML + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); // Get all paragraph elements Aspose.Html.Collections.HTMLCollection paragraphs = document.GetElementsByTagName("p"); @@ -23,24 +20,20 @@ static void Main(string[] args) // Iterate backwards and remove empty paragraphs for (int i = paragraphs.Length - 1; i >= 0; i--) { - Aspose.Html.Dom.Element p = (Aspose.Html.Dom.Element)paragraphs[i]; - if (String.IsNullOrWhiteSpace(p.TextContent)) + Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)paragraphs[i]; + if (element.TextContent.Trim().Length == 0 && element.ParentNode != null) { - if (p.ParentNode != null) - { - p.ParentNode.RemoveChild(p); - } + element.ParentNode.RemoveChild(element); } } // Save the modified document string outputPath = "output.html"; document.Save(outputPath); - Console.WriteLine("Document saved to: " + outputPath); } - catch (Exception ex) + catch (System.Exception ex) { - Console.WriteLine("Error: " + ex.Message); + System.Console.WriteLine(ex.Message); } } } \ No newline at end of file diff --git a/html-navigation/remove_all_script_tags_from_dom_eliminate_executable_javascript_before_saving.cs b/html-navigation/remove-all-script-tags-from-dom-to-eliminate-executable-javascript-before-saving.cs similarity index 56% rename from html-navigation/remove_all_script_tags_from_dom_eliminate_executable_javascript_before_saving.cs rename to html-navigation/remove-all-script-tags-from-dom-to-eliminate-executable-javascript-before-saving.cs index 7c084b4..134f816 100644 --- a/html-navigation/remove_all_script_tags_from_dom_eliminate_executable_javascript_before_saving.cs +++ b/html-navigation/remove-all-script-tags-from-dom-to-eliminate-executable-javascript-before-saving.cs @@ -9,39 +9,19 @@ static void Main() { try { - // Input and output file paths - string inputPath = "input.html"; + string inputPath = "sample.html"; string outputPath = "output.html"; - // Create a minimal sample HTML file if it does not exist if (!File.Exists(inputPath)) { - string sampleHtml = @" - - - Sample - - - -

Welcome

- -

Content without scripts.

- -"; - File.WriteAllText(inputPath, sampleHtml); + File.WriteAllText(inputPath, + "

Hello

"); } - // Load document Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath); - // Get all script elements var scripts = document.GetElementsByTagName("script"); - // Iterate safely and remove for (int i = scripts.Length - 1; i >= 0; i--) { var script = scripts[i]; @@ -51,7 +31,6 @@ static void Main() } } - // Save document document.Save(outputPath); } catch (System.Exception ex) diff --git a/html-navigation/remove-deprecated-marquee-tags-replace-with-css-animations-modern-effect.cs b/html-navigation/remove-deprecated-marquee-tags-replace-with-css-animations-modern-effect.cs new file mode 100644 index 0000000..90e433f --- /dev/null +++ b/html-navigation/remove-deprecated-marquee-tags-replace-with-css-animations-modern-effect.cs @@ -0,0 +1,78 @@ +// Remove all deprecated tags and replace them with CSS animations for modern effect. + +using System; +using System.IO; +using System.Linq; +using Aspose.Html; + +class Program +{ + static void Main() + { + try + { + // Sample HTML containing tags + string htmlContent = @" + + + + Marquee Replacement Example + + + Scrolling Text 1 +

Some other content.

+ Scrolling Text 2 + +"; + + // Load HTML document from inline content + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Create CSS animation style + Aspose.Html.Dom.Element styleElement = document.CreateElement("style"); + styleElement.TextContent = @" +.marquee-animation { + display: inline-block; + white-space: nowrap; + overflow: hidden; + animation: scroll-left 5s linear infinite; +} +@keyframes scroll-left { + from { transform: translateX(100%); } + to { transform: translateX(-100%); } +}"; + // Append style to + Aspose.Html.HTMLElement head = (Aspose.Html.HTMLElement)document.GetElementsByTagName("head").First(); + head.AppendChild(styleElement); + + // Find all elements + Aspose.Html.Collections.HTMLCollection marqueeElements = document.GetElementsByTagName("marquee"); + // Convert collection to array to avoid modification during iteration + var marqueeArray = marqueeElements.Cast().ToArray(); + + foreach (Aspose.Html.Dom.Element marquee in marqueeArray) + { + // Cast to HTMLElement to access TextContent + Aspose.Html.HTMLElement marqueeHtml = (Aspose.Html.HTMLElement)marquee; + string text = marqueeHtml.TextContent; + + // Create replacement
with animation class + Aspose.Html.HTMLElement replacement = (Aspose.Html.HTMLElement)document.CreateElement("div"); + replacement.ClassName = "marquee-animation"; + replacement.TextContent = text; + + // Replace with the new element + marquee.ParentNode.ReplaceChild(replacement, marquee); + } + + // Save the modified document + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine($"Document saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/remove-duplicate-id-attributes-appending-numeric-suffixes-ensure-uniqueness-throughout-document.cs b/html-navigation/remove-duplicate-id-attributes-appending-numeric-suffixes-ensure-uniqueness-throughout-document.cs new file mode 100644 index 0000000..f1c8a14 --- /dev/null +++ b/html-navigation/remove-duplicate-id-attributes-appending-numeric-suffixes-ensure-uniqueness-throughout-document.cs @@ -0,0 +1,43 @@ +// Remove duplicate ID attributes by appending numeric suffixes to ensure uniqueness throughout the document. + +using System; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "
First

Second

Third"; + var document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + Aspose.Html.Collections.HTMLCollection allElements = document.GetElementsByTagName("*"); + var seenIds = new HashSet(); + for (int i = 0; i < allElements.Length; i++) + { + var element = (Aspose.Html.HTMLElement)allElements[i]; + string id = element.GetAttribute("id"); + if (string.IsNullOrEmpty(id)) + continue; + if (!seenIds.Add(id)) + { + int suffix = 1; + string newId; + do + { + newId = id + "_" + suffix; + suffix++; + } while (!seenIds.Add(newId)); + element.SetAttribute("id", newId); + } + } + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine("Processed document saved to " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/html-navigation/remove-inline-style-attributes-elements-enforce-external-stylesheet-usage.cs b/html-navigation/remove-inline-style-attributes-elements-enforce-external-stylesheet-usage.cs new file mode 100644 index 0000000..deb4a98 --- /dev/null +++ b/html-navigation/remove-inline-style-attributes-elements-enforce-external-stylesheet-usage.cs @@ -0,0 +1,51 @@ +// Remove all inline style attributes from elements to enforce external stylesheet usage. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Sample HTML content with inline styles + string htmlContent = @" + + + Sample + + +
Hello World
+

Paragraph with style.

+ No style here. + +"; + + // Load HTML document from string (using two-argument constructor) + Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlContent, "about:blank"); + + // Select all elements that have a 'style' attribute + var elementsWithStyle = document.QuerySelectorAll("[style]"); + + // Remove the inline 'style' attribute from each element + for (int i = 0; i < elementsWithStyle.Length; i++) + { + Aspose.Html.Dom.Element element = (Aspose.Html.Dom.Element)elementsWithStyle[i]; + element.RemoveAttribute("style"); + } + + // Define output path + string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.html"); + + // Save the modified document + document.Save(outputPath); + + Console.WriteLine($"Document saved successfully to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/html-navigation/remove-noscript-elements-simplify-dom-environments-without-javascript.cs b/html-navigation/remove-noscript-elements-simplify-dom-environments-without-javascript.cs new file mode 100644 index 0000000..d738d1e --- /dev/null +++ b/html-navigation/remove-noscript-elements-simplify-dom-environments-without-javascript.cs @@ -0,0 +1,51 @@ +// Remove all noscript elements to simplify the DOM for environments without JavaScript. + +using System; +using System.IO; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; + +class Program +{ + static void Main(string[] args) + { + try + { + string inputPath = "input.html"; + string outputPath = "output.html"; + + // Create a minimal sample input file if it does not exist + if (!File.Exists(inputPath)) + { + string sampleHtml = "

Sample content

"; + File.WriteAllText(inputPath, sampleHtml); + } + + using (HTMLDocument document = new HTMLDocument(inputPath)) + { + // Get all