/// <summary> /// Transforms XPM markup contained in HTML attributes to HTML comments inside the HTML elements. /// </summary> /// <param name="htmlFragment">The HTML fragment to tranform.</param> /// <returns>The transformed HTML fragment.</returns> internal static string TransformXpmMarkupAttributes(string htmlFragment) { //HTML Agility pack drops closing option tags for some reason (bug?) HtmlNode.ElementsFlags.Remove("option"); HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml($"<html>{htmlFragment}</html>"); HtmlNode rootElement = htmlDoc.DocumentNode.FirstChild; HtmlNodeCollection elementsWithXpmMarkup = rootElement.SelectNodes(XpmMarkupXPath); if (elementsWithXpmMarkup != null) { XpmMarkupMap xpmMarkupMap = XpmMarkupMap.Current; foreach (HtmlNode elementWithXpmMarkup in elementsWithXpmMarkup) { string xpmMarkupRef = ReadAndRemoveAttribute(elementWithXpmMarkup, XpmMarkupHtmlAttrName); string xpmMarkup = xpmMarkupMap[xpmMarkupRef]; if (string.IsNullOrEmpty(xpmMarkup)) { continue; } HtmlCommentNode xpmMarkupNode = htmlDoc.CreateComment(xpmMarkup); elementWithXpmMarkup.ChildNodes.Insert(0, xpmMarkupNode); } } return(rootElement.InnerHtml); }
/// <summary> /// Converts the MathML blocks to be readable by OneNote /// </summary> /// <param name="htmlDoc"></param> private void ConvertMathMl(HtmlDocument htmlDoc) { HtmlNodeCollection mathNodes = htmlDoc.DocumentNode.SelectNodes("//math"); if (mathNodes == null) { return; } foreach (var mathNode in mathNodes.ToList()) { mathNode.Attributes.RemoveAll(); HtmlAttribute mathMlNamespaceAttr = htmlDoc.CreateAttribute("xmlns:mml", MathMlNameSpace); mathNode.Attributes.Add(mathMlNamespaceAttr); foreach (var node in mathNode.DescendantsAndSelf()) { node.Name = "mml:" + node.Name; } string newMathMlString = String.Format(MathMlOutline, mathNode.OuterHtml); HtmlCommentNode newMathNode = htmlDoc.CreateComment(newMathMlString); mathNode.ParentNode.ReplaceChild(newMathNode, mathNode); } }
public override void Process(ref HtmlNode node, HtmlAttribute dynamicAttribute, Dictionary <string, AliasReference> classNameAlias, Dictionary <int, string> classNameAliasdepth, int depth, string websiteId, ExpressionEvaluator evaluator, KEntity entity, dynamic websiteData, Models.Pagination viewDetails, string queryString, Dictionary <string, long> functionLog, bool isDetailsView = false, bool isNFSite = false, string developerId = null) { if (Kitsune.Helper.Constants.WidgetRegulerExpression.IsMatch(dynamicAttribute.Value)) { string attributeValue = evaluator.EvaluateExpression(dynamicAttribute.Value, entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out bool hasData, functionLog, isDetailsView, isNFSite, developerId).ToString(); if (!hasData || (System.Boolean.TryParse(attributeValue, out bool attVal) && attVal)) { node = HtmlCommentNode.CreateNode("<!-- skip -->"); } } }
private void ProcessCommentNode(HtmlCommentNode node) { if (!Policy.PreservesComments) { node.ParentNode.RemoveChild(node); } else { string value = node.Comment; // Strip conditional directives regardless of the PRESERVE_COMMENTS setting. if (value != null) { node.Comment = CONDITIONAL_DIRECTIVES.Replace(value, string.Empty); } } }
private static IEnumerable <string> Translate(HtmlNode node) { return(node switch { HtmlCommentNode _ => Enumerable.Empty <string>(), HtmlTextNode n => TranslateText(n.InnerText), HtmlNode n when n.Name == "p" => TranslateParagraph(n), HtmlNode n when n.Name == "br" => Enumerable.Empty <string>(), // TODO(zhangshuai.ds): Convert to definition list. HtmlNode n when n.Name == "div" && n.HasClass("sectiontoc") => Enumerable.Empty <string>(), HtmlNode n when n.Name == "div" && n.Element("pre") != null => TranslateCode(n), HtmlNode n when n.Name == "div" && n.Element("i") != null => Enumerable.Concat( new string[] { @"\begin{quote}" }, Enumerable.Concat( n.ChildNodes.SelectMany(Translate), new string[] { @"\end{quote}" })), HtmlNode n when HeaderNames.Contains(n.Name) => TranslateHeader(n), HtmlNode n when n.Name == "ul" || n.Name == "ol" => TranslateList(n), HtmlNode n when n.Name == "li" => Enumerable.Concat(new[] { "\\item" }, n.ChildNodes.SelectMany(Translate)), HtmlNode n when n.Name == "table" => TranslateTable(n), HtmlNode n when n.Name == "center" => TranslateCentering(n), HtmlNode n when n.Name == "tt" => Enumerable.Repeat(@"\texttt{" + string.Join(" ", n.ChildNodes.SelectMany(Translate)) + "}", 1), HtmlNode n when n.Name == "em" => Enumerable.Repeat(@"\emph{" + string.Join(" ", n.ChildNodes.SelectMany(Translate)) + "}", 1), HtmlNode n when n.Name == "b" => Enumerable.Repeat(@"\textbf{" + string.Join(" ", n.ChildNodes.SelectMany(Translate)) + "}", 1), HtmlNode n when n.Name == "i" => Enumerable.Repeat(@"\textit{" + string.Join(" ", n.ChildNodes.SelectMany(Translate)) + "}", 1), HtmlNode n when !n.HasChildNodes => Enumerable.Empty <string>(), HtmlNode n when n.Name == "a" => Enumerable.Repeat( string.Format( CultureInfo.InvariantCulture, @"\hyperref[{0}]{{{1}}}", StringUtils.SubstringAfter(n.Attributes.Single(attr => attr.Name == "href").Value, "#"), string.Join(" ", n.ChildNodes.SelectMany(Translate))), 1), HtmlNode n when n.Name == "code" => Enumerable.Repeat(@"\texttt{" + string.Join(" ", n.ChildNodes.SelectMany(Translate)) + "}", 1), _ => throw new NotImplementedException("Unsupported HtmlNode: " + node.Name), });
public static void CreateAxeHtmlReport(this ISearchContext context, AxeResult results, string destination) { HashSet <string> selectors = new HashSet <string>(); int violationCount = GetCount(results.Violations, ref selectors); int incompleteCount = GetCount(results.Incomplete, ref selectors); int passCount = GetCount(results.Passes, ref selectors); int inapplicableCount = GetCount(results.Inapplicable, ref selectors); var doc = new HtmlDocument(); var node = HtmlNode.CreateNode("<html lang=\"en\"><head><meta charset=\"utf-8\"><title>Accessiblity Check</title><style></style></head><body></body></html>"); doc.DocumentNode.AppendChild(node); HtmlCommentNode hcn = doc.CreateComment("<!DOCTYPE html>\r\n"); HtmlNode htmlNode = doc.DocumentNode.SelectSingleNode("/html"); doc.DocumentNode.InsertBefore(hcn, htmlNode); StringBuilder content = new StringBuilder(); content.AppendLine(@".fullImage{"); content.AppendLine($"content: url('{GetDataImageString(context)};border: 1px solid black;margin-left:1em;"); content.AppendLine(@"} .fullImage:hover {transform:scale(2.75);transform-origin: top left;} p {} .wrap .wrapTwo .wrapThree{margin:2px;max-width:70vw;} .wrapOne {margin-left:1em;overflow-wrap:anywhere;} .wrapTwo {margin-left:2em;overflow-wrap:anywhere;} .wrapThree {margin-left:3em;overflow-wrap:anywhere;} .emOne {margin-left:1em;overflow-wrap:anywhere;} .emTwo {margin-left:2em;overflow-wrap:anywhere;} .emThree {margin-left:3em;overflow-wrap:anywhere;} .majorSection{border: 1px solid black;} .findings{border-top:1px solid black;} .htmlTable{border-top:double lightgray;width:100%;display:table;}"); HtmlNode body = doc.DocumentNode.SelectSingleNode("//body"); doc.DocumentNode.SelectSingleNode("//style").InnerHtml = content.ToString(); var element = doc.CreateElement("h1"); element.InnerHtml = "Accessiblity Check"; body.AppendChild(element); element = doc.CreateElement("h3"); element.InnerHtml = "Context:"; body.AppendChild(element); content = new StringBuilder(); content.AppendLine($"Url: {results.Url}<br>"); content.AppendLine($"Orientation: {results.TestEnvironment.OrientationType}<br>"); content.AppendLine($"Size: {results.TestEnvironment.WindowWidth} x {results.TestEnvironment.WindowHeight}<br>"); content.AppendLine($"Time: {results.Timestamp}<br>"); content.AppendLine($"User agent: {results.TestEnvironment.UserAgent}<br>"); content.AppendLine($"Using: {results.TestEngineName} ({results.TestEngineVersion})"); element = doc.CreateElement("div"); element.SetAttributeValue("class", "emOne"); element.SetAttributeValue("id", "reportContext"); element.InnerHtml = content.ToString(); body.AppendChild(element); element = doc.CreateElement("h3"); element.InnerHtml = "Counts:"; body.AppendChild(element); element = doc.CreateElement("div"); element.SetAttributeValue("class", "emOne"); content = new StringBuilder(); content.AppendLine($" Violation: {violationCount}<br>"); content.AppendLine($" Incomplete: {incompleteCount}<br>"); content.AppendLine($" Pass: {passCount}<br>"); content.AppendLine($" Inapplicable: {inapplicableCount}"); element.InnerHtml = content.ToString(); body.AppendChild(element); element = doc.CreateElement("h3"); element.InnerHtml = "Image:"; body.AppendChild(element); element = doc.CreateElement("img"); element.SetAttributeValue("class", "fullImage"); element.SetAttributeValue("width", "33%"); element.SetAttributeValue("height", "auto"); body.AppendChild(element); if (!string.IsNullOrEmpty(results.Error)) { element = doc.CreateElement("h2"); element.InnerHtml = "SCAN ERRORS:"; body.AppendChild(element); var error = doc.CreateElement("div"); error.SetAttributeValue("id", "ErrorMessage"); error.InnerHtml = HttpUtility.HtmlEncode(results.Error); body.AppendChild(error); } element = doc.CreateElement("br"); body.AppendChild(element); element = doc.CreateElement("br"); body.AppendChild(element); var area = doc.CreateElement("div"); body.AppendChild(area); if (violationCount > 0) { area.AppendChild(doc.CreateElement("br")); GetReadableAxeResults(results.Violations, "Violations", doc, area); } if (incompleteCount > 0) { area.AppendChild(doc.CreateElement("br")); GetReadableAxeResults(results.Incomplete, "Incomplete", doc, area); } if (passCount > 0) { area.AppendChild(doc.CreateElement("br")); GetReadableAxeResults(results.Passes, "Passes", doc, area); } if (inapplicableCount > 0) { area.AppendChild(doc.CreateElement("br")); GetReadableAxeResults(results.Inapplicable, "Inapplicable", doc, area); } doc.Save(destination, Encoding.UTF8); }
internal static string GetXmlComment(HtmlCommentNode comment) { string s = comment.Comment; return s.Substring(4, s.Length - 7).Replace("--", " - -"); }
public override void Process(ref HtmlNode node, HtmlAttribute dynamicAttribute, Dictionary <string, AliasReference> classNameAlias, Dictionary <int, string> classNameAliasdepth, int depth, string websiteId, ExpressionEvaluator evaluator, KEntity entity, dynamic websiteData, Models.Pagination viewDetails, string queryString, Dictionary <string, long> functionLog, bool isDetailsView = false, bool isNFSite = false, string developerId = null) { Node result = LexerGenerator.Parse(Helper.TrimDelimiters(dynamicAttribute.Value)); if (result.Token.Value == ACTIONS.Loop) { string referenceObject = result.Children[0].Children[0].Token.Value; string referenceName = result.Children[2].Children[0].Token.Value?.ToLower(); var refObj = evaluator.EvaluateExpression(referenceObject, entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out bool hasData, functionLog, isDetailsView, isNFSite); if (refObj.GetType() == typeof(string) && refObj == "") { node = HtmlCommentNode.CreateNode("<!-- skip -->"); return; } string offsetObj = evaluator.EvaluateExpression(result.Children[6], entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out hasData, functionLog, isDetailsView, isNFSite, developerId).ToString(); int.TryParse(offsetObj, out int offset); int iteration = 0; int maxIteration = 0; if (dynamicAttribute.Value.IndexOf("offset") > 0) { if (int.TryParse(viewDetails.currentpagenumber, out int currentPage) && currentPage > 0) { iteration = offset * (currentPage - 1); } } else { string iterationObj = evaluator.EvaluateExpression(result.Children[4], entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out hasData, functionLog, isDetailsView, isNFSite, developerId).ToString(); int.TryParse(iterationObj, out iteration); } maxIteration = iteration + offset; int objSize = (int)evaluator.GetObjectSize(refObj); maxIteration = (maxIteration < objSize) ? maxIteration : objSize; if (iteration > maxIteration) { node = HtmlCommentNode.CreateNode("<!-- skip -->"); return; } else if (objSize == maxIteration && dynamicAttribute.Value.IndexOf("offset") > 0) { viewDetails.nextpage.url = "#"; viewDetails.pagesize = maxIteration - iteration + 1; } AliasReference aliasReference = new AliasReference { referenceObject = null, iteration = iteration, maxIteration = maxIteration }; if (!classNameAlias.ContainsKey(referenceName)) { classNameAlias.Add(referenceName, aliasReference); classNameAliasdepth.Add(depth, referenceName); } } else if (result.Token.Value == ACTIONS.InLoop) { string referenceName = result.Children[0].Children[0].Token.Value?.ToLower(); string referenceObject = result.Children[2].Children[0].Token.Value; var obj = evaluator.EvaluateExpression(referenceObject, entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out bool hasData, functionLog, isDetailsView, isNFSite); if (obj.GetType() == typeof(string) && obj == "") { node = HtmlCommentNode.CreateNode("<!-- skip -->"); return; } AliasReference aliasReference = new AliasReference(); aliasReference.referenceObject = referenceObject; aliasReference.iteration = 0; aliasReference.maxIteration = (int)evaluator.GetObjectSize(obj); if (!classNameAlias.ContainsKey(referenceName)) { classNameAlias.Add(referenceName, aliasReference); classNameAliasdepth.Add(depth, referenceName); } } }
/// <summary> /// Extracts all the HTML code before and after the "body" tag of the pattern HTML page /// and saves if on textBeforeBody and textAfterBody members. /// This function MUST to be called before start to make calls to ProcessHeadTag. /// </summary> /// <param name="originalSourcePage">The HTML pattern page to extract the code</param> public void PrepareHtmlPattern(HtmlDocument originalSourcePage) { // Get the encoding of the pattern page: try { inputEncoding = originalSourcePage.DeclaredEncoding; } catch { inputEncoding = null; } bool beforeBody = true; // Are we currently before or after the "body" node? // Traverse the root nodes of the HTML page: foreach (HtmlNode e in originalSourcePage.DocumentNode.ChildNodes) { if (e is HtmlCommentNode) { // head tag and other stuff. HtmlCommentNode com = (HtmlCommentNode)e; if (beforeBody) { textBeforeBody += com.OuterHtml + "\n"; } else { textAfterBody += com.OuterHtml + "\n"; } } else if (e.Name.ToLower() == "html") { // Copy the <html> tag (TODO: check if clone() can be used here to make the copy) textBeforeBody += "<html "; // Get the attributes of the html tag: foreach (HtmlAttribute atr in e.Attributes) { //if (atr.specified) ? textBeforeBody += atr.Name + "=\"" + atr.Value + "\""; } textBeforeBody += " >\n"; // Traverse the <html> children: foreach (HtmlNode child in e.ChildNodes) { if (child.Name.ToLower() == "body") { beforeBody = false; } else if (child.Name.ToLower() == "head") { textBeforeBody += ProcessHeadTag(child); } else if (beforeBody) { textBeforeBody += child.OuterHtml + "\n"; } else { textAfterBody += child.OuterHtml + "\n"; } } // Close the HTML tag: textAfterBody += "</html>\n"; } // TODO: Other tags should not be added too? } }
protected virtual void VisitComment(HtmlCommentNode node) { }
/// <summary> /// Process the node for k-tags and k-expressions and return the processed node. /// </summary> /// <param name="readNode"></param> /// <param name="classNameAlias"></param> /// <param name="classNameAliasDepth"></param> /// <param name="depth"></param> /// <param name="isRepeat"></param> /// <param name="evaluator"></param> /// <returns></returns> private HtmlNode GetProcessedNode(HtmlNode readNode, Dictionary <string, AliasReference> classNameAlias, Dictionary <int, string> classNameAliasDepth, int depth, bool isRepeat, ExpressionEvaluator evaluator, string customerId, KEntity entity, dynamic websiteData, Models.Pagination viewDetails, string queryString, Dictionary <string, long> functionLog, bool isDetailsView, bool isNFSite) { try { HtmlNode returnNode = readNode.CloneNode(false); if (readNode.NodeType == HtmlNodeType.Comment) { return(returnNode); } else if (readNode.NodeType == HtmlNodeType.Text) { returnNode = HtmlTextNode.CreateNode(ReplaceKLanguage(readNode.OuterHtml, classNameAlias, evaluator, entity, viewDetails, websiteData, websiteData?._system?.kresult, queryString, functionLog, isDetailsView, isNFSite)) ?? returnNode; return(returnNode); } else if (readNode.NodeType == HtmlNodeType.Element) { if (isRepeat && (false || readNode.Attributes.Aggregate(false, (acc, x) => acc || x.Name.ToLower().Equals("k-norepeat")))) { returnNode = HtmlCommentNode.CreateNode("<!-- skip -->"); } if (returnNode.Attributes.Count() > 0) { foreach (HtmlAttribute attribute in returnNode.Attributes.ToList()) { if (returnNode.NodeType == HtmlNodeType.Comment) { break; } if (!String.IsNullOrEmpty(attribute.Name) && dynamicTagDescriptors.Contains(attribute.Name.ToLower())) { TagProcessor processor = processorFactory.GetProcessor(attribute.Name); processor.ProcessNode(ref returnNode, attribute, classNameAlias, classNameAliasDepth, depth, customerId, evaluator, entity, websiteData, viewDetails, queryString, functionLog, isDetailsView, isNFSite); if (!(attribute.Name.ToLower().Equals(LanguageAttributes.KPayAmount.GetDescription()) || attribute.Name.ToLower().Equals(LanguageAttributes.KPayPurpose.GetDescription()))) { returnNode.Attributes[attribute.Name.ToLower()]?.Remove(); } } else if (!attribute.Name.Equals("input", StringComparison.InvariantCultureIgnoreCase) && !attribute.Name.Equals("headers", StringComparison.InvariantCultureIgnoreCase) && Kitsune.Helper.Constants.WidgetRegulerExpression.IsMatch(attribute.Value)) { attribute.Value = ReplaceKLanguage(attribute.Value, classNameAlias, evaluator, entity, viewDetails, websiteData, websiteData?._system?.kresult, queryString, functionLog, isDetailsView, isNFSite); //attribute.Value = evaluator.EvaluateExpression(attribute.Value, entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, isDetailsView, isNFSite); if (returnNode.Name?.ToLower() == "img" && attribute.Name?.ToLower() == "src") { attribute.Value = attribute.Value?.Trim(); } } } if (requestType == KitsuneRequestUrlType.PRODUCTION && returnNode.Name?.ToLower() == "img") { string source = returnNode.Attributes.Where(x => x.Name.ToLower() == "src")?.FirstOrDefault()?.Value; if (!string.IsNullOrEmpty(source) && !source.StartsWith("/") && !source.StartsWith(".") && !source.StartsWith("data:") && source.ToLower().IndexOf("k-img") < 0) { source = source.Replace(" ", "%20"); string ext = source.Split('?')[0].Split('.').Last().ToLower(); string domain = source.Replace("http://", "").Replace("https://", "").Split('/')[0].ToLower(); if (!BlackListKImgFileExtension.Contains(ext) && !BlackListKImgDomain.Contains(domain) && !domain.Contains("cdn") && !domain.Contains("akamai") && !domain.Contains("cloudflare")) { string rootUrl = websiteData?.rootaliasurl?.url?.Value; if (!source.StartsWith(rootUrl, StringComparison.InvariantCultureIgnoreCase)) { string srcSetValue = ""; foreach (int resolution in KLM_Constants.IMAGE_RESOLUTIONS) { srcSetValue += String.Format(KLM_Constants.K_IMG_FORMAT_STRING, resolution, source); } if (srcSetValue != null) { returnNode.Attributes.Add("srcset", srcSetValue); //returnNode.Attributes.Remove("src"); } } } } } } //if (returnNode.Name?.ToLower() == "img") //{ // string source = returnNode.Attributes.Where(x => x.Name.ToLower() == "src").FirstOrDefault().Value; // if (!string.IsNullOrEmpty(source)) // { // string[] srcParts = source.Split('?')[0].Split('.'); // if (!srcParts[srcParts.Length - 1].Equals("svg", StringComparison.InvariantCultureIgnoreCase)) // { // string rootUrl = websiteData?.rootaliasurl?.url?.Value; // string path = websiteData?._system?.request?.urlpath?.Value; // string srcSetValue = GetSrcSetValue(rootUrl, path, source); // if (srcSetValue != null) // { // returnNode.Attributes.Add("srcset", srcSetValue); // //returnNode.Attributes.Remove("src"); // } // } // } //} if (returnNode.Name?.ToLower() == LanguageAttributes.KScript.GetDescription()?.ToLower()) { TagProcessor processor = processorFactory.GetProcessor(returnNode.Name); processor.ProcessNode(ref returnNode, null, classNameAlias, classNameAliasDepth, depth, customerId, evaluator, entity, websiteData, viewDetails, queryString, functionLog, isDetailsView, isNFSite); } } return(returnNode); } catch (Exception ex) { throw; } }
private void load_DOMInternal(HtmlNode node, TreeViewItem tvi) { TreeViewItem new_tvi = new TreeViewItem(); switch (node.NodeType) { case HtmlNodeType.Comment: HtmlCommentNode commentNode = (HtmlCommentNode)node; string outerHtml = commentNode.OuterHtml; Color foreColor; if (outerHtml.ToUpper().Contains("DOCTYPE")) { foreColor = Colors.Gray; this.tvHTML_DOM.Items.Add(new_tvi); this._DOM_map.Add(node, new_tvi); } else { return; // DOM树不包含注释。 } new_tvi.Header = new Run(outerHtml) { Foreground = getBrush(foreColor) }; return; case HtmlNodeType.Document: case HtmlNodeType.Element: break; case HtmlNodeType.Text: if (tvi == null) { return; // DOM树文档不支持文本。 } HtmlTextNode textNode = (HtmlTextNode)node; string text = textNode.Text.Trim(); if (text == string.Empty) { return; } new_tvi.Header = text; tvi.Items.Add(new_tvi); this._DOM_map.Add(node, new_tvi); return; default: throw new InvalidOperationException(); } if (node.NodeType == HtmlNodeType.Element) { TextBlock tb = new TextBlock(); tb.Inlines.Add(new Run(string.Format("<{0}", node.Name)) { Foreground = getBrush(Colors.Blue) }); HtmlAttributeCollection attributes = node.Attributes; foreach (HtmlAttribute attribute in attributes) { tb.Inlines.Add(" "); tb.Inlines.Add(new Run(attribute.Name) { Foreground = getBrush(Colors.Red) }); tb.Inlines.Add("="); tb.Inlines.Add(new Run(string.Format("\"{0}\"", HttpUtility.HtmlEncode(attribute.Value))) { Foreground = getBrush(Colors.Purple) }); } tb.Inlines.Add(new Run(">") { Foreground = getBrush(Colors.Blue) }); new_tvi.Header = tb; if (tvi == null) { this.tvHTML_DOM.Items.Add(new_tvi); } else { tvi.Items.Add(new_tvi); } this._DOM_map.Add(node, new_tvi); } TreeViewItem childItem = (node.NodeType == HtmlNodeType.Document) ? null : new_tvi; foreach (HtmlNode childNode in node.ChildNodes) { this.load_DOMInternal(childNode, childItem); } if (node.NodeType == HtmlNodeType.Element) { TreeViewItem new_tvi_open = new_tvi; TreeViewItem new_tvi_close = new TreeViewItem() { Visibility = Visibility.Collapsed }; if (tvi == null) { this.tvHTML_DOM.Items.Add(new_tvi_close); } else { tvi.Items.Add(new_tvi_close); } new_tvi_open.Expanded += (sender, e) => { TreeViewItem item = (TreeViewItem)sender; if (item.Items.Count == 0) { return; } new_tvi_close.Visibility = Visibility.Visible; }; new_tvi_open.Collapsed += (sender, e) => { TreeViewItem item = (TreeViewItem)sender; if (item.Items.Count == 0) { return; } new_tvi_close.Visibility = Visibility.Collapsed; }; new_tvi_close.SetBinding( TreeViewItem.BackgroundProperty, new Binding() { Source = new_tvi_open, Path = new PropertyPath(TreeViewItem.BackgroundProperty) } ); new_tvi_close.Header = new Run(string.Format("</{0}>", node.Name)) { Foreground = getBrush(Colors.Blue) }; new_tvi_open.IsExpanded = true; } }
private void load_SORTEDInternal(HtmlNode node, Paragraph p) { switch (node.NodeType) { case HtmlNodeType.Comment: HtmlCommentNode commentNode = (HtmlCommentNode)node; string outerHtml = commentNode.OuterHtml; Color foreColor; if (outerHtml.ToUpper().Contains("DOCTYPE")) { foreColor = Colors.Gray; } else { foreColor = Colors.Green; } p.Inlines.Add(new Run(outerHtml) { Foreground = getBrush(foreColor) }); return; case HtmlNodeType.Document: case HtmlNodeType.Element: break; case HtmlNodeType.Text: HtmlTextNode textNode = (HtmlTextNode)node; string text = textNode.Text; p.Inlines.Add(text); return; default: throw new InvalidOperationException(); } if (node.NodeType == HtmlNodeType.Element) { p.Inlines.Add(new Run(string.Format("<{0}", node.Name)) { Foreground = getBrush(Colors.Blue) }); HtmlAttributeCollection attributes = node.Attributes; foreach (HtmlAttribute attribute in attributes) { p.Inlines.Add(" "); p.Inlines.Add(new Run(attribute.Name) { Foreground = getBrush(Colors.Red) }); p.Inlines.Add("="); p.Inlines.Add(new Run(string.Format("\"{0}\"", HttpUtility.HtmlEncode(attribute.Value))) { Foreground = getBrush(Colors.Purple) }); } if (node.ChildNodes.Count == 0) { if (attributes.Count == 0) { p.Inlines.Add(" "); } p.Inlines.Add(new Run("/>") { Foreground = getBrush(Colors.Blue) }); } else { p.Inlines.Add(new Run(">") { Foreground = getBrush(Colors.Blue) }); } } foreach (HtmlNode childNode in node.ChildNodes) { this.load_SORTEDInternal(childNode, p); } if (node.NodeType == HtmlNodeType.Element && node.ChildNodes.Count != 0) { p.Inlines.Add(new Run(string.Format("</{0}>", node.Name)) { Foreground = getBrush(Colors.Blue) }); } }