/// <summary>Wrap the supplied HTML around this node.</summary> /// <param name="html"> /// HTML to wrap around this element, e.g. /// <c><div class="head"></div></c> /// . Can be arbitrarily deep. /// </param> /// <returns>this node, for chaining.</returns> public virtual iText.StyledXmlParser.Jsoup.Nodes.Node Wrap(String html) { Validate.NotEmpty(html); iText.StyledXmlParser.Jsoup.Nodes.Element context = Parent() is iText.StyledXmlParser.Jsoup.Nodes.Element ? (iText.StyledXmlParser.Jsoup.Nodes.Element)Parent() : null; IList <iText.StyledXmlParser.Jsoup.Nodes.Node> wrapChildren = iText.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment (html, context, BaseUri()); iText.StyledXmlParser.Jsoup.Nodes.Node wrapNode = wrapChildren[0]; if (wrapNode == null || !(wrapNode is iText.StyledXmlParser.Jsoup.Nodes.Element)) { // nothing to wrap with; noop return(null); } iText.StyledXmlParser.Jsoup.Nodes.Element wrap = (iText.StyledXmlParser.Jsoup.Nodes.Element)wrapNode; iText.StyledXmlParser.Jsoup.Nodes.Element deepest = GetDeepChild(wrap); parentNode.ReplaceChild(this, wrap); deepest.AddChildren(this); // remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is remainder if (wrapChildren.Count > 0) { for (int i = 0; i < wrapChildren.Count; i++) { iText.StyledXmlParser.Jsoup.Nodes.Node remainder = wrapChildren[i]; remainder.parentNode.RemoveChild(remainder); wrap.AppendChild(remainder); } } return(this); }
// merge multiple <head> or <body> contents into one, delete the remainder, and ensure they are owned by <html> private void NormaliseStructure(String tag, iText.StyledXmlParser.Jsoup.Nodes.Element htmlEl) { Elements elements = this.GetElementsByTag(tag); iText.StyledXmlParser.Jsoup.Nodes.Element master = elements.First(); // will always be available as created above if not existent if (elements.Count > 1) { // dupes, move contents to master IList <iText.StyledXmlParser.Jsoup.Nodes.Node> toMove = new List <iText.StyledXmlParser.Jsoup.Nodes.Node>(); for (int i = 1; i < elements.Count; i++) { iText.StyledXmlParser.Jsoup.Nodes.Node dupe = elements[i]; foreach (iText.StyledXmlParser.Jsoup.Nodes.Node node in dupe.childNodes) { toMove.Add(node); } dupe.Remove(); } foreach (iText.StyledXmlParser.Jsoup.Nodes.Node dupe in toMove) { master.AppendChild(dupe); } } // ensure parented by <html> if (!master.Parent().Equals(htmlEl)) { htmlEl.AppendChild(master); } }