wasStitchNET – Rev 7

Subversion Repositories:
Rev:
///////////////////////////////////////////////////////////////////////////
//  Copyright (C) Wizardry and Steamworks 2017 - License: GNU GPLv3      //
//  Please see: http://www.gnu.org/licenses/gpl.html for legal details,  //
//  rights of fair usage, the disclaimer and warranty conditions.        //
///////////////////////////////////////////////////////////////////////////

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

namespace wasStitchNET.Patchers
{
    public static class XML
    {
        public static XDocument PatchConfiguration(XDocument cfg, XDocument nfg, HashSet<string> configuredTags)
        {
            /*foreach (var e in nfg.Descendants()
                .Where(e => !configuredTags.Contains(e.Name.LocalName) &&
                    !e.Ancestors().Any(o => configuredTags.Contains(o.Name.LocalName))))*/
            foreach (var e in nfg.Descendants()
                .Where(e => configuredTags.Contains(e.Name.LocalName)))
            {
                // Select the element in the current configuration that is found in the default configuration.
                var cfgElement = cfg.XPathSelectElement(e.GetAbsoluteXPath());
                switch (cfgElement != null)
                {
                    // Element found in current configuration.
                    case true:
                        // Only set the element value if it has no descendants.
                        if (!cfgElement.Descendants().Any())
                            cfgElement.Value = e.Value;
                        break;
                    // Element not found in the current configuration.
                    default:
                        // Find the first existing parent of the default configuration in the current configuration.
                        var parent = e.Parent;
                        XElement cfgParentElement = null;
                        do
                        {
                            cfgParentElement = cfg.XPathSelectElement(parent.GetAbsoluteXPath());
                            parent = e.Parent;
                        } while (cfgParentElement == null);

                        // Add the default configuration parent to the current configuration.
                        cfgParentElement = nfg.XPathSelectElement(cfgParentElement.GetAbsoluteXPath());
                        break;
                }
            }
            return cfg;
        }
    }
}