Bloom.Book.HtmlDom.MigrateChildren C# (CSharp) Method

MigrateChildren() private static method

For each div in the page which has the specified class, find the corresponding div with that class in newPage, and replace its contents with the contents of the source page. Also inserts any needed styles we know about.
private static MigrateChildren ( XmlElement page, string parentClass, XmlElement newPage ) : void
page System.Xml.XmlElement
parentClass string
newPage System.Xml.XmlElement
return void
        private static void MigrateChildren(XmlElement page, string parentClass, XmlElement newPage)
        {
            //the leading '.' here is needed because newPage is an element in a larger DOM, and we only want to search in this page
            var xpath = ".//div[contains(concat(' ', @class, ' '), ' " + parentClass + " ')]";
            var oldParents = page.SafeSelectNodes(xpath);
            var newParents = newPage.SafeSelectNodes(xpath);
            // The Math.Min is not needed yet; in fact, we don't yet have any cases where there is more than one
            // thing to copy or where the numbers are not equal. It's just a precaution.
            for(int i = 0; i < Math.Min(newParents.Count, oldParents.Count); i++)
            {
                var oldParent = (XmlElement) oldParents[i];
                var newParent = (XmlElement) newParents[i];
                foreach(var child in newParent.ChildNodes.Cast<XmlNode>().ToArray())
                    newParent.RemoveChild(child);
                // apparently we are modifying the ChildNodes collection by removing the child from there to insert in the new location,
                // which messes things up unless we make a copy of the collection.
                foreach(XmlNode child in oldParent.ChildNodes.Cast<XmlNode>().ToArray())
                {
                    newParent.AppendChild(child);
                    AddKnownStyleIfMissing(child);
                }
            }
        }