System.Xml.XmlNode.SelectSingleNode(string)

Here are the examples of the csharp api System.Xml.XmlNode.SelectSingleNode(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

840 Examples 7

19 Source : FoldersManagerForm.cs
with GNU General Public License v3.0
from ClusterM

void XmlToTree(string xmlString)
        {
            gamesCollection.Unsplit();
            var oldCollection = new NesMenuCollection();
            oldCollection.AddRange(gamesCollection);
            var xml = new XmlDoreplacedent();
            xml.LoadXml(xmlString);
            gamesCollection.Clear();
            XmlToNode(xml, xml.SelectSingleNode("/Tree").ChildNodes, oldCollection, gamesCollection);
            // oldCollection has only unsorted (new) games
            if (oldCollection.Count > 0)
            {
                NesMenuFolder unsorted;
                var unsorteds = from f in gamesCollection where f is NesMenuFolder && f.Name == Resources.FolderNameUnsorted select f;
                if (unsorteds.Count() > 0)
                    unsorted = unsorteds.First() as NesMenuFolder;
                else
                {
                    unsorted = new NesMenuFolder(Resources.FolderNameUnsorted);
                    unsorted.Position = NesMenuFolder.Priority.Leftmost;
                    gamesCollection.Add(unsorted);
                }
                foreach (var game in oldCollection)
                    unsorted.ChildMenuCollection.Add(game);
                MessageBox.Show(this, Resources.NewGamesUnsorted, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            DrawTree();
        }

19 Source : CompilationDatabaseSettings.cs
with Apache License 2.0
from CoatiSoftware

public static List<CompilationDatabaseSettings> ParseCdbsMetaData(string data)
		{
			List<CompilationDatabaseSettings> cdbs = new List<CompilationDatabaseSettings>();

			if(data.Length > 0)
			{
				XmlDoreplacedent doc = new XmlDoreplacedent();
				doc.LoadXml(data);
				XmlNode root = doc.SelectSingleNode("cdbs");

				XmlNodeList nodes = root.SelectNodes("cdb");

				foreach (XmlNode node in nodes)
				{
					cdbs.Add(ParseCdbMetaData(node));
				}
			}

			return cdbs;
		}

19 Source : CompilationDatabaseSettings.cs
with Apache License 2.0
from CoatiSoftware

public static CompilationDatabaseSettings ParseCdbMetaData(XmlNode node)
		{
			CompilationDatabaseSettings cdb = new CompilationDatabaseSettings();

			XmlNode nameNode = node.SelectSingleNode("name");
			string name = nameNode.InnerText;

			XmlNode sourceNode = node.SelectSingleNode("sourceProject");
			string source = sourceNode.InnerText;

			XmlNode directoryNode = node.SelectSingleNode("directory");
			string directory = directoryNode.InnerText;

			XmlNode updatedNode = node.SelectSingleNode("lastUpdated");
			string updated = updatedNode.InnerText;
			System.DateTime updatedDate;
			if(System.DateTime.TryParse(updated, out updatedDate) == false)
			{
				updatedDate = System.DateTime.MinValue;
			}

			XmlNode includedProjects = node.SelectSingleNode("includedProjects");
			XmlNodeList includedProjectNodes = includedProjects.SelectNodes("includedProject");
			List<string> includedProjectsList = new List<string>();
			foreach(XmlNode p in includedProjectNodes)
			{
				includedProjectsList.Add(p.InnerText);
			}

			XmlNode configurationNode = node.SelectSingleNode("configuration");
			string configuration = configurationNode.InnerText;

			XmlNode platformNode = node.SelectSingleNode("platform");
			string platform = platformNode.InnerText;

			XmlNode additionalClangOptionsNode = node.SelectSingleNode("additionalClangOptions");
			string additionalClangOptions = additionalClangOptionsNode.InnerText;

			XmlNode nonSystemIncludesUseAngleBracketsNode = node.SelectSingleNode("nonSystemIncludesUseAngleBrackets");
			bool nonSystemIncludesUseAngleBrackets = true;
			System.Boolean.TryParse(nonSystemIncludesUseAngleBracketsNode.InnerText, out nonSystemIncludesUseAngleBrackets);

			// if cdb file is not there anymore, set the modified date back so that a full update will be performed
			if (System.IO.File.Exists(directory + "\\" + name + ".json") == false)
			{
				updatedDate = System.DateTime.MinValue;
			}

			cdb.Name = name;
			cdb.SourceProject = source;
			cdb.Directory = directory;
			cdb.LastUpdated = updatedDate;
			cdb.IncludedProjects = includedProjectsList;
			cdb.ConfigurationName = configuration;
			cdb.PlatformName = platform;
			cdb.AdditionalClangOptions = additionalClangOptions;
			cdb.NonSystemIncludesUseAngleBrackets = nonSystemIncludesUseAngleBrackets;

			return cdb;
		}

19 Source : XDCMake.cs
with zlib License
from codecat

static void Main(string[] args)
	{
		var inputFiles = new List<string>();
		var outputFile = string.Empty;
		var replacedemblyName = string.Empty;

		foreach (var arg in args)
		{
			if (arg.Length < 2)
			{
				continue;
			}

			if (arg[0] == '@')
			{
				ProcessStartInfo startInfo = new ProcessStartInfo();
				startInfo.FileName = replacedembly.GetExecutingreplacedembly().Location;
				startInfo.Arguments = File.ReadAllText(arg.Substring(1));
				startInfo.UseShellExecute = false;
				startInfo.RedirectStandardOutput = true;

				Process process = Process.Start(startInfo);
				Console.Write(process.StandardOutput.ReadToEnd());
				process.WaitForExit();
				return;
			}

			if (arg[0] != '/' && arg[0] != '-')
			{
				replacedemblyName = arg;
				continue;
			}

			string id = arg.Substring(1);
			string param = string.Empty;

			if (id[0] == 'F')
			{
				if (id.Length > 2)
				{
					param = id.Substring(2);
					id = id.Substring(0, 2);
				}
			}

			switch (id)
			{
				case "Fs":
					inputFiles.Add(param);
					break;
				case "Fo":
					outputFile = param;
					break;
			}
		}

		if (outputFile.Length == 0)
		{
			Console.WriteLine("error XDC0007 : No output file specified");
			return;
		}

		if (replacedemblyName.Length == 0)
		{
			replacedemblyName = Path.GetFileNameWithoutExtension(outputFile);
		}

		var outputDoreplacedent = new XmlDoreplacedent();
		outputDoreplacedent.LoadXml("<doc><replacedembly>" + replacedemblyName + "</replacedembly><members/></doc>");
		XmlNode outputNode = outputDoreplacedent.DoreplacedentElement.SelectSingleNode("members");

		foreach (var file in inputFiles)
		{
			var doc = new XmlDoreplacedent();

			try
			{
				doc.Load(file);
			}
			catch (Exception)
			{
				Console.WriteLine(file + " : warning XDC0004 : Unable to load XML fragment");
				continue;
			}

			XmlNode members = doc.SelectSingleNode("doc/members");

			if (members == null)
			{
				Console.WriteLine(file + " : warning XDC0022 : File contains no <doc><members> tag");
				continue;
			}

			foreach (XmlNode member in members.ChildNodes)
			{
				member.Attributes.RemoveNamedItem("decl");
				member.Attributes.RemoveNamedItem("source");
				member.Attributes.RemoveNamedItem("line");

				outputNode.AppendChild(outputDoreplacedent.ImportNode(member, true));
			}
		}

		try
		{
			outputDoreplacedent.Save(outputFile);
		}
		catch (Exception)
		{
			Console.WriteLine("error XDC0002 : Cannot write to output file");
		}
	}

19 Source : DocumentInfo.cs
with MIT License
from cwensley

public virtual void ReadXml(XmlElement element)
		{
			AutoScroll = element.GetBoolAttribute ("autoscroll") ?? true;
			var formatsElement = (XmlElement)element.SelectSingleNode("formats");
			if (formatsElement != null) formats.ReadXml(formatsElement);
			var zoomInfoElement = (XmlElement)element.SelectSingleNode("zoomInfo");
			if (zoomInfoElement != null) zoomInfo.ReadXml(zoomInfoElement);
		}

19 Source : Main.cs
with MIT License
from cwensley

public void ReadXml()
        {
            if (File.Exists(SettingsFile))
            {
                var doc = new XmlDoreplacedent();
                doc.Load(SettingsFile);
                var head = (XmlElement)doc.SelectSingleNode("pablo");

                Settings.ReadXml(head);

                var elem = (XmlElement)head.SelectSingleNode("main");
                if (elem != null)
                {
                    var dir = elem.GetAttribute("path");
                    if (Directory.Exists(dir))
                        FileList.Initialize(dir);
                }

                head.ReadChildXml("main-window", new WindowStateSaver(this));
            }
        }

19 Source : XmlExtensions.cs
with MIT License
from cwensley

public static T ReadChildXml<T>(this XmlElement element, string childElementName, CreateFromXml<T> create)
			where T : IXmlReadable
		{
			var childElement = element.SelectSingleNode(childElementName) as XmlElement;
			if (childElement == null) return default(T);
			var child = create(childElement);
			if (!EqualityComparer<T>.Default.Equals(child, default(T))) child.ReadXml(childElement);
			return child;
		}

19 Source : XmlExtensions.cs
with MIT License
from cwensley

public static void ReadChildXml<T>(this XmlElement element, string childElementName, T child)
			where T : IXmlReadable
		{
			var childElement = element.SelectSingleNode(childElementName) as XmlElement;

			if (childElement != null) child.ReadXml(childElement);
		}

19 Source : XmlExtensions.cs
with MIT License
from cwensley

public static void ReadChildListXml<T>(this XmlElement element, IList<T> list, CreateFromXml<T> create, string childElement, string listElement = null)
			where T : IXmlReadable
		{
			XmlNodeList childNodes = null;
			if (listElement != null)
			{
				var listNode = element.SelectSingleNode(listElement);
				if (listNode != null)
					childNodes = listNode.SelectNodes(childElement);
			}
			else
				childNodes = element.SelectNodes(childElement);

			if (childNodes != null)
			{
				if (!list.IsReadOnly)
					list.Clear();
				else
				{
					for (int i = 0; i < list.Count; i++)
					{
						list[i] = default(T);
					}
				}
				int index = 0;
				foreach (XmlElement childNode in childNodes)
				{
					var item = create(childNode);
					if (!EqualityComparer<T>.Default.Equals(item, default(T)))
					{
						item.ReadXml(childNode);
						if (list.IsReadOnly)
						{
							if (index < list.Count)
								list[index++] = item;
							else
								break;
						}
						else
						{
							list.Add(item);
						}
					}
				}
			}
		}

19 Source : NewsViewerControl.xaml.cs
with MIT License
from darklinkpower

private void UpdateBindings()
        {
            if (currentNewsNode == null)
            {
                Newsreplacedle = string.Empty;
                NewsText = string.Empty;
                NewsDate = string.Empty;
                return;
            }

            var replacedleChild = CurrentNewsNode.SelectSingleNode(@"replacedle");
            var descriptionChild = CurrentNewsNode.SelectSingleNode(@"description");
            var dateChild = CurrentNewsNode.SelectSingleNode(@"pubDate");
            if (replacedleChild != null  && descriptionChild != null)
            {
                Newsreplacedle = HtmlToPlainText(replacedleChild.InnerText);
                NewsText = HtmlToPlainText(descriptionChild.InnerText);
                NewsDate = Regex.Replace(HtmlToPlainText(dateChild.InnerText), @" \+\d+$", "");
            }
        }

19 Source : NewsViewerControl.xaml.cs
with MIT License
from darklinkpower

void OpenSelectedNews()
        {
            if (CurrentNewsNode != null)
            {
                if (SettingsModel.Settings.UseCompactWebNewsViewer)
                {
                    var descriptionChild = CurrentNewsNode.SelectSingleNode(@"description");
                    if (descriptionChild == null)
                    {
                        return;
                    }
                    var html = @"
                    <head>
                        <replacedle>News Viewer</replacedle>
                        <meta charset=""UTF-8"">
                        <style type=""text/css"">
                            html,body
                            {
                                color: rgb(207, 210, 211);
                                margin: 0;
                                padding: 10;
                                font-family: ""Arial"";
                                font-size: 14px;
                                background-color: rgb(51, 54, 60);
                            }
                            a {
                                color: rgb(147, 179, 200);
                                text-decoration: none;
                            }
                            img {
                                max-width: 100%;
                            }
                        </style>
                    </head>
                    <body>";
                    html += Regex.Replace(CurrentNewsNode.SelectSingleNode(@"pubDate")?.InnerText ?? "", @" \+\d+$", "") + "<br>";
                    html += "<h1>" + (CurrentNewsNode.SelectSingleNode(@"replacedle")?.InnerText ?? "") + "</h1>" + "<br>";
                    html += descriptionChild.InnerText;
                    html += @"</body>";

                    var webView = PlayniteApi.WebViews.CreateView(650, 700);
                    webView.Navigate("data:text/html," + html);
                    webView.OpenDialog();
                    webView.Dispose();
                }
                else
                {
                    var linkChild = CurrentNewsNode.SelectSingleNode(@"link");
                    if (linkChild != null)
                    {
                        var webView = PlayniteApi.WebViews.CreateView(1024, 700);
                        webView.Navigate(linkChild.InnerText);
                        webView.OpenDialog();
                        webView.Dispose();
                    }
                }
            }
        }

19 Source : AchievementManifest.cs
with GNU General Public License v3.0
from DarwinBaker

public void UpdateReference()
        {
            //clear lists
            this.ClearProgress();

            //load lists of advancements to track for this version
            try
            {
                if (!XmlObject.TryGetDoreplacedent(Paths.AchievementsFile, out XmlDoreplacedent doreplacedent))
                    throw new IOException();

                //recursively build achievement tree
                XmlNode rootNode = doreplacedent.DoreplacedentElement.SelectSingleNode("root");
                this.RootAdvancement = new Achievement(rootNode);
                this.RootAdvancement.GetAllChildrenRecursive(this.AllAdvancements);

                //add sub-criteria
                foreach (Advancement advancement in this.AllAdvancements.Values)
                {
                    if (!advancement.TryGetCriteria(out CriteriaSet criteria))
                        continue;

                    foreach (KeyValuePair<string, Criterion> criterion in criteria.All)
                        this.AllCriteria[(advancement.Id, criterion.Key)] = criterion.Value;
                }
            }
            catch (Exception e)
            { 
                Main.QuitBecause("Error loading achievement manifest reference files!", e); 
            }
        }

19 Source : Advancement.cs
with GNU General Public License v3.0
from DarwinBaker

protected void ParseCriteria(XmlNode advancementNode)
        {
            //initialize criteria if this advancement has any
            XmlNode criteriaNode = advancementNode.SelectSingleNode("criteria");
            if (criteriaNode is null)
                return;

            this.Criteria = new CriteriaSet(criteriaNode, this);
            this.Designate(Uuid.Empty);
        }

19 Source : FavoritesList.cs
with GNU General Public License v3.0
from DarwinBaker

public override void ReadDoreplacedent(XmlDoreplacedent doreplacedent)
        {
            //populate advancements
            this.Advancements.Clear();
            foreach (XmlNode node in doreplacedent.DoreplacedentElement.SelectSingleNode("advancements").ChildNodes)
                this.Advancements.Add(node.InnerText);

            //populate criteria
            this.Criteria.Clear();
            foreach (XmlNode node in doreplacedent.DoreplacedentElement.SelectSingleNode("criteria").ChildNodes)
                this.Criteria.Add(node.InnerText);

            //populate statistics
            this.Statistics.Clear();
            foreach (XmlNode node in doreplacedent.DoreplacedentElement.SelectSingleNode("statistics").ChildNodes)
                this.Statistics.Add(node.InnerText);
        }

19 Source : StatisticsManifest.cs
with GNU General Public License v3.0
from DarwinBaker

public void UpdateReference()
        {
            //clear list     
            this.ClearProgress();

            //load list of items to count for this version
            try
            {
                if (XmlObject.TryGetDoreplacedent(Paths.StatisticsFile, out XmlDoreplacedent doreplacedent))
                {
                    foreach (XmlNode itemNode in doreplacedent.SelectSingleNode("items").ChildNodes)
                        this.Items.Add(itemNode.Attributes["id"]?.Value, new Statistic(itemNode));
                }
            }
            catch (Exception e)
            {
                Main.QuitBecause("Error loading statistics manifest reference files!", e);
            }
        }

19 Source : UpdateRequest.cs
with GNU General Public License v3.0
from DarwinBaker

private bool HandleResponse(string latestXml)
        {
            if (latestXml is null or "")
                return false;

            try
            {
                LatestPatch = new XmlDoreplacedent();
                LatestPatch.LoadXml(latestXml);

                //get version
                Latestreplacedle = LatestPatch.DoreplacedentElement.GetAttribute("replacedle");
                string vnum = LatestPatch.DoreplacedentElement.GetAttribute("version");

                //populate change lists
                LatestUpgrades.Clear();
                foreach (XmlNode upgrade in LatestPatch.DoreplacedentElement.SelectSingleNode("upgrades").ChildNodes)
                    LatestUpgrades.Add((upgrade.InnerText, upgrade.Attributes["icon"]?.Value ?? "bullet_point"));
                LatestFixes.Clear();
                foreach (XmlNode fix in LatestPatch.DoreplacedentElement.SelectSingleNode("fixes").ChildNodes)
                    LatestFixes.Add((fix.InnerText, fix.Attributes["icon"]?.Value ?? "bullet_fix"));

                if (Version.TryParse(vnum, out Version version))
                {
                    LatestVersion = version;
                    return true;
                }
            }
            catch (NullReferenceException)
            {
                //malformed response, nothing to do here
            }
            catch (XmlException)
            {
                //malformed response, nothing to do here
            }

            if (UserInitiated)
                MessageBox.Show("There was a problem checking for updates! Try again later, and make sure your firewall isn't blocking AATool.", "Couldn't Get Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
            return false;
        }

19 Source : SettingsGroup.cs
with GNU General Public License v3.0
from DarwinBaker

public override void ReadDoreplacedent(XmlDoreplacedent doreplacedent)
        {
            foreach (XmlNode settingNode in doreplacedent.SelectSingleNode("settings").ChildNodes)
            {
                //parse node to proper data type and add value with replacedociated key
                string key   = settingNode.Attributes["key"].Value;
                string value = settingNode.Attributes["value"]?.Value;
                switch (settingNode.Name)
                {
                    case "string":
                        this.Set(key, value);
                        break;
                    case "bool":
                        if (bool.TryParse(value, out bool boolean))
                            this.Set(key, boolean);
                        break;
                    case "int":
                        if (int.TryParse(value, out int number))
                            this.Set(key, number);
                        break;
                    case "color":
                        string[] split = value.Split(',');
                        this.Set(key, Color.FromNonPremultiplied(int.Parse(split[0]), int.Parse(split[1]), int.Parse(split[2]), 255));
                        break;
                    case "list":
                        this.Set(key, ParseListNode<string>(settingNode));
                        break;
                }
            }
        }

19 Source : UIControl.cs
with GNU General Public License v3.0
from DarwinBaker

public void BuildFromSourceDoreplacedent()
        {
            //attempt to construct control from blueprint xml file
            SourceDocs ??= new Dictionary<Type, XmlDoreplacedent>();
            Type type = this.GetType();
            if (!SourceDocs.ContainsKey(type))
            {
                //this control type doesn't have a cached blueprint; try and load one
                try
                {
                    var newDoreplacedent = new XmlDoreplacedent();
                    foreach (string file in Directory.GetFiles(Paths.DIR_UI_CONTROLS, "*.xml"))
                    {
                        if (Path.GetFileNameWithoutExtension(file).Replace("_", string.Empty) == "control" + type.Name.ToLower().Substring(2))
                        {
                            newDoreplacedent.Load(file);
                            SourceDocs[type] = newDoreplacedent;
                            break;
                        }
                    }
                }
                catch { }
            }          
            if (SourceDocs.TryGetValue(type, out XmlDoreplacedent doreplacedent))
                this.ReadNode(doreplacedent.SelectSingleNode("control"));
        }

19 Source : CCredits.cs
with GNU General Public License v3.0
from DarwinBaker

private void ReadCredits()
        {
            //parse credits file
            try
            {
                var doreplacedent = new XmlDoreplacedent();
                using (var stream = File.OpenRead(Paths.CreditsFile))
                {
                    doreplacedent.Load(stream);
                    XmlNode root = doreplacedent.SelectSingleNode("credits");
                    foreach (XmlNode groupNode in root.ChildNodes)
                        flow.Controls.Add(ParseGroup(groupNode));
                }
            }
            catch { }
        }

19 Source : UIGrid.cs
with GNU General Public License v3.0
from DarwinBaker

public override void ReadNode(XmlNode node)
        {
            base.ReadNode(node);

            this.Rows       = new ();
            XmlNode rowNode = node.SelectSingleNode("rows");
            if (rowNode is not null && rowNode.HasChildNodes)
            {
                foreach (XmlNode row in rowNode.ChildNodes)
                {
                    this.Rows.Add(ParseAttribute(row, "height", new Size(1, SizeMode.Relative)));
                    this.CollapsedRows.Add(ParseAttribute(row, "collapsed", false));
                }   
            }
            else
            {
                this.Rows.Add(new Size(1, SizeMode.Relative));
                this.CollapsedRows.Add(false);
            }

            this.Columns    = new ();
            XmlNode colNode = node.SelectSingleNode("columns");
            if (colNode is not null && colNode.HasChildNodes)
            {
                foreach (XmlNode col in colNode.ChildNodes)
                {
                    this.Columns.Add(ParseAttribute(col, "width", new Size(1, SizeMode.Relative)));
                    this.CollapsedColumns.Add(ParseAttribute(col, "collapsed", false));
                }
            }
            else
            {
                this.Columns.Add(new Size(1, SizeMode.Relative));
                this.CollapsedColumns.Add(false);
            }
        }

19 Source : RollupFunctions.cs
with Microsoft Public License
from demianrasko

public string ExtractNodeValue(XmlNode parentNode, string name)
        {
            XmlNode childNode = parentNode.SelectSingleNode(name);

            if (null == childNode)
            {
                return null;
            }
            return childNode.InnerText;
        }

19 Source : CDlgGetSteamID.cs
with GNU General Public License v3.0
from Depressurizer

protected override void RunProcess()
        {
            XmlDoreplacedent doc = new XmlDoreplacedent();

            try
            {
                string url = string.Format(CultureInfo.InvariantCulture, Constants.SteamProfileCustom, customUrlName);
                Logger.Info(GlobalStrings.CDlgGetSteamID_AttemptingDownloadXMLProfile, customUrlName, url);
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                doc.Load(response.GetResponseStream());
                response.Close();
                Logger.Info(GlobalStrings.CDlgGetSteamID_XMLProfileDownloaded);
            }
            catch (Exception e)
            {
                Logger.Error(GlobalStrings.CDlgGetSteamID_ExceptionDownloadingXMLProfile, e.Message);
                throw new ApplicationException(GlobalStrings.CDlgGetSteamID_FailedToDownloadProfile + e.Message, e);
            }

            XmlNode idNode = doc.SelectSingleNode("/profile/steamID64");
            if (idNode != null)
            {
                Success = long.TryParse(idNode.InnerText, out long tmp);
                if (Success)
                {
                    SteamID = tmp;
                }
            }

            OnThreadCompletion();
        }

19 Source : DlgProfile.cs
with GNU General Public License v3.0
from Depressurizer

public string GetDisplayName(long accountId)
        {
            try
            {
                XmlDoreplacedent doc = new XmlDoreplacedent();
                HttpWebRequest req = (HttpWebRequest) WebRequest.Create(string.Format(CultureInfo.InvariantCulture, Constants.SteamProfile, accountId));
                using (WebResponse resp = req.GetResponse())
                {
                    doc.Load(resp.GetResponseStream());
                }

                XmlNode nameNode = doc.SelectSingleNode("profile/steamID");
                if (nameNode != null)
                {
                    return nameNode.InnerText;
                }
            }
            catch (Exception e)
            {
                Logger.Warn(GlobalStrings.DlgProfile_ExceptionRaisedWhenTryingScrapeProfileName, accountId);
                Logger.Warn(e.Message);
            }

            return null;
        }

19 Source : Profile.cs
with GNU General Public License v3.0
from Depressurizer

public static Profile Load(string path)
        {
            Logger.Info(GlobalStrings.Profile_LoadingProfile, path);
            Profile profile = new Profile
            {
                FilePath = path
            };

            XmlDoreplacedent doc = new XmlDoreplacedent();

            try
            {
                doc.Load(path);
            }
            catch (Exception e)
            {
                Logger.Warn(GlobalStrings.Profile_FailedToLoadProfile, e.Message);
                throw new ApplicationException(GlobalStrings.Profile_ErrorLoadingProfile + e.Message, e);
            }

            XmlNode profileNode = doc.SelectSingleNode("/" + XmlNameProfile);

            if (profileNode != null)
            {
                // Get the 64-bit Steam ID
                long accId = XmlUtil.GetInt64FromNode(profileNode[XmlNameSteamId], 0);
                if (accId == 0)
                {
                    string oldAcc = XmlUtil.GetStringFromNode(profileNode[XmlNameOldSteamIdShort], null);
                    if (oldAcc != null)
                    {
                        accId = Steam.ToSteamId64(oldAcc);
                    }
                }

                profile.SteamID64 = accId;

                // Get other attributes
                profile.AutoUpdate = XmlUtil.GetBoolFromNode(profileNode[XmlNameAutoUpdate], profile.AutoUpdate);

                profile.AutoImport = XmlUtil.GetBoolFromNode(profileNode[XmlNameAutoImport], profile.AutoImport);

                profile.LocalUpdate = XmlUtil.GetBoolFromNode(profileNode[XmlNameLocalUpdate], profile.LocalUpdate);
                profile.WebUpdate = XmlUtil.GetBoolFromNode(profileNode[XmlNameWebUpdate], profile.WebUpdate);
                profile.SteamWebApiKey = XmlUtil.GetStringFromNode(profileNode[XmlNameWebKey], profile.SteamWebApiKey);

                profile.IncludeUnknown = XmlUtil.GetBoolFromNode(profileNode[XmlNameIncludeUnknown], profile.IncludeUnknown);
                profile.BypreplacedIgnoreOnImport = XmlUtil.GetBoolFromNode(profileNode[XmlNameBypreplacedIgnoreOnImport], profile.BypreplacedIgnoreOnImport);

                profile.ExportDiscard = XmlUtil.GetBoolFromNode(profileNode[XmlNameExportDiscard], profile.ExportDiscard);
                profile.AutoIgnore = XmlUtil.GetBoolFromNode(profileNode[XmlNameAutoIgnore], profile.AutoIgnore);
                profile.OverwriteOnDownload = XmlUtil.GetBoolFromNode(profileNode[XmlNameOverwriteNames], profile.OverwriteOnDownload);

                profile.IncludeShortcuts = XmlUtil.GetBoolFromNode(profileNode[XmlNameIncludeShortcuts], profile.IncludeShortcuts);

                XmlNode exclusionListNode = profileNode.SelectSingleNode(XmlNameExclusionList);
                XmlNodeList exclusionNodes = exclusionListNode?.SelectNodes(XmlNameExclusion);
                if (exclusionNodes != null)
                {
                    foreach (XmlNode node in exclusionNodes)
                    {
                        if (XmlUtil.TryGetIntFromNode(node, out int id))
                        {
                            profile.IgnoreList.Add(id);
                        }
                    }
                }

                XmlNode gameListNode = profileNode.SelectSingleNode(XmlNameGameList);
                XmlNodeList gameNodes = gameListNode?.SelectNodes(XmlNameGame);
                if (gameNodes != null)
                {
                    foreach (XmlNode node in gameNodes)
                    {
                        GameInfo.AddFromNode(node, profile);
                    }
                }

                XmlNode filterListNode = profileNode.SelectSingleNode(XmlNameFilterList);
                XmlNodeList filterNodes = filterListNode?.SelectNodes(XmlNameFilter);
                if (filterNodes != null)
                {
                    foreach (XmlNode node in filterNodes)
                    {
                        Filter.AddFromNode(node, profile);
                    }
                }

                XmlNode autocatListNode = profileNode.SelectSingleNode(XmlNameAutoCatList);
                if (autocatListNode != null)
                {
                    XmlNodeList autoCatNodes = autocatListNode.ChildNodes;
                    foreach (XmlNode node in autoCatNodes)
                    {
                        XmlElement autocatElement = node as XmlElement;
                        if (node == null)
                        {
                            continue;
                        }

                        AutoCat autocat = AutoCat.LoadACFromXmlElement(autocatElement);
                        if (autocat != null)
                        {
                            profile.AutoCats.Add(autocat);
                        }
                    }
                }
                else
                {
                    AutoCat.GenerateDefaultAutoCatSet(profile.AutoCats);
                }

                //profile.AutoCats.Sort();
            }

            Logger.Info(GlobalStrings.MainForm_ProfileLoaded);
            return profile;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static TEnum GetEnumFromNode<TEnum>(XmlNode node, TEnum defaultValue) where TEnum : struct, IComparable, IConvertible, IFormattable
        {
            if (node == null)
            {
                return defaultValue;
            }

            XmlNode textNode = node.SelectSingleNode("text()");
            if (textNode == null)
            {
                return defaultValue;
            }

            string str = textNode.InnerText;
            if (Enum.TryParse(str, out TEnum res))
            {
                return res;
            }

            return defaultValue;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static bool TryGetBoolFromNode(XmlNode node, out bool value)
        {
            value = false;

            XmlNode textNode = node?.SelectSingleNode("text()");
            if (textNode != null && bool.TryParse(textNode.InnerText, out value))
            {
                return true;
            }

            return false;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static bool TryGetFloatFromNode(XmlNode node, out float value)
        {
            value = 0;
            XmlNode textNode = node?.SelectSingleNode("text()");
            if (textNode != null && float.TryParse(textNode.InnerText, out value))
            {
                return true;
            }

            return false;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static bool TryGetDoubleFromNode(XmlNode node, out double value)
        {
            value = 0;

            XmlNode textNode = node?.SelectSingleNode("text()");
            if (textNode != null && double.TryParse(textNode.InnerText, out value))
            {
                return true;
            }

            return false;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static bool TryGetInt64FromNode(XmlNode node, out long value)
        {
            value = 0;

            XmlNode textNode = node?.SelectSingleNode("text()");
            if (textNode != null && long.TryParse(textNode.InnerText, out value))
            {
                return true;
            }

            return false;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static bool TryGetIntFromNode(XmlNode node, out int value)
        {
            value = 0;

            XmlNode textNode = node?.SelectSingleNode("text()");
            if (textNode != null && int.TryParse(textNode.InnerText, out value))
            {
                return true;
            }

            return false;
        }

19 Source : XmlUtil.cs
with GNU General Public License v3.0
from Depressurizer

public static bool TryGetStringFromNode(XmlNode node, out string value)
        {
            value = string.Empty;

            XmlNode textNode = node?.SelectSingleNode("text()");
            if (textNode == null)
            {
                return false;
            }

            value = node.InnerText;
            return true;
        }

19 Source : GameInfo.cs
with GNU General Public License v3.0
from Depressurizer

public static void AddFromNode(XmlNode node, IProfile profile)
        {
            if (!XmlUtil.TryGetIntFromNode(node[XmlNameGameId], out int id))
            {
                return;
            }

            GameListingSource source = XmlUtil.GetEnumFromNode(node[XmlNameGameSource], GameListingSource.Unknown);

            if (source < GameListingSource.Manual && profile.IgnoreList.Contains(id))
            {
                return;
            }

            string name = XmlUtil.GetStringFromNode(node[XmlNameGameName], null);
            GameInfo game = new GameInfo(id, name, profile.GameData)
            {
                Source = source
            };
            profile.GameData.Games.Add(id, game);

            game.IsHidden = XmlUtil.GetBoolFromNode(node[XmlNameGameHidden], false);
            game.Executable = XmlUtil.GetStringFromNode(node[XmlNameGameExecutable], null);
            game.LastPlayed = XmlUtil.GetIntFromNode(node[XmlNameGameLastPlayed], 0);
            game.HoursPlayed = XmlUtil.GetDoubleFromNode(node[XmlNameGameHoursPlayed], 0);

            XmlNode catListNode = node.SelectSingleNode(XmlNameGameCategoryList);
            XmlNodeList catNodes = catListNode?.SelectNodes(XmlNameGameCategory);
            if (catNodes == null)
            {
                return;
            }

            foreach (XmlNode cNode in catNodes)
            {
                if (XmlUtil.TryGetStringFromNode(cNode, out string cat))
                {
                    game.AddCategory(profile.GameData.GetCategory(cat));
                }
            }
        }

19 Source : SvgCacheManager.cs
with MIT License
from dotnet-campus

private XmlElement getCacheElm(Uri uri)
		{
			if(uri == lastUri && lastCacheElm != null)
			{
				return lastCacheElm;
			}
			else
			{
				//string xpath = "/cache/resource[@url='" + uri.ToString() + "']";
                string xpath = "/cache/resource[@url='" + uri.ToString().Replace("'", "'") + "']";
                XmlNode node = cacheDoc.SelectSingleNode(xpath);
				if(node != null)
				{
					lastCacheElm = node as XmlElement;
				}
				else
				{
					lastCacheElm = cacheDoc.CreateElement("resource");
					cacheDoc.DoreplacedentElement.AppendChild(lastCacheElm);
					lastCacheElm.SetAttribute("url", uri.ToString());
				}

				lastUri = uri;
				return lastCacheElm;
			}
		}

19 Source : WpfCacheManager.cs
with MIT License
from dotnet-campus

private XmlElement GetCacheElm(Uri uri)
		{
			if(uri == lastUri && lastCacheElm != null)
			{
				return lastCacheElm;
			}
			else
			{
				//string xpath = "/cache/resource[@url='" + uri.ToString() + "']";
                string xpath = "/cache/resource[@url='" + uri.ToString().Replace("'", "'") + "']";
                XmlNode node = cacheDoc.SelectSingleNode(xpath);
				if(node != null)
				{
					lastCacheElm = node as XmlElement;
				}
				else
				{
					lastCacheElm = cacheDoc.CreateElement("resource");
					cacheDoc.DoreplacedentElement.AppendChild(lastCacheElm);
					lastCacheElm.SetAttribute("url", uri.ToString());
				}

				lastUri = uri;
				return lastCacheElm;
			}
		}

19 Source : ReswParser.cs
with MIT License
from DotNetPlus

public static ReswInfo Parse(string content)
        {
            var res = new ReswInfo
            {
                Items = new List<ReswItem>()
            };

            var xml = new XmlDoreplacedent();
            xml.LoadXml(content);

            var nodes = xml.DoreplacedentElement?.SelectNodes("//data");
            if (nodes == null)
            {
                return res;
            }

            foreach (XmlElement element in nodes)
            {
                string key = null, value = null, comment = null;
                var elementKey = element.Attributes.GetNamedItem("name");
                if (elementKey != null)
                {
                    key = elementKey.Value ?? string.Empty;
                }
                else
                {
                    continue;
                }
                var elementValue = element.SelectSingleNode("value");
                if (elementValue != null)
                {
                    value = elementValue.InnerText;
                }
                else
                {
                    continue;
                }

                var elementComment = element.SelectSingleNode("comment");
                if (elementComment != null)
                {
                    comment = elementComment.InnerText;
                }

                res.Items.Add(new ReswItem(key, value, comment));
            }
            return res;
        }

19 Source : AppState.cs
with BSD 2-Clause "Simplified" License
from double-hi

public static string GetConfigNodeValue(XmlNode configNode, string nodeName)
        {
            XmlNode valueNode = configNode.SelectSingleNode(nodeName);
            if (valueNode != null)
            {
                if (valueNode.Attributes.GetNamedItem("value") != null)
                {
                    return valueNode.Attributes.GetNamedItem("value").Value;
                }
            }

            return null;
        }

19 Source : ProjectTestContext.cs
with MIT License
from dragonglasscom

public void SetRootNamespaceInProject(string rootNamespace)
        {
            var projectDoc = new XmlDoreplacedent();
            projectDoc.Load(ProjectFilePath);
            var propertyGroupElement = projectDoc.DoreplacedentElement.SelectSingleNode("PropertyGroup");
            var rootNsElement = propertyGroupElement.SelectSingleNode("RootNamespace");
            if (rootNsElement == null)
            {
                rootNsElement = projectDoc.CreateElement("RootNamespace");
                propertyGroupElement.AppendChild(rootNsElement);
            }

            rootNsElement.InnerText = rootNamespace;
            projectDoc.Save(ProjectFilePath);
        }

19 Source : DotNetProjectFolderInfo.cs
with MIT License
from dragonglasscom

private string GetOrInferRootNamespace(string fullProjectFilePath, string projectName)
        {
            var xmlDoc = new XmlDoreplacedent();
            xmlDoc.Load(fullProjectFilePath);
            var rootNamespaceElement = xmlDoc.DoreplacedentElement.SelectSingleNode("PropertyGroup/RootNamespace");
            if (rootNamespaceElement != null)
                return rootNamespaceElement.InnerText;

            var replacedemblyNameElement = xmlDoc.DoreplacedentElement.SelectSingleNode("PropertyGroup/replacedemblyName");
            if (replacedemblyNameElement != null)
                return replacedemblyNameElement.InnerText;

            return projectName;
        }

19 Source : DotNetProjectFolderInfo.cs
with MIT License
from dragonglasscom

private string GetOrInferreplacedemblyName(string fullProjectFilePath, string projectName)
        {
            var xmlDoc = new XmlDoreplacedent();
            xmlDoc.Load(fullProjectFilePath);
            var rootNamespaceElement = xmlDoc.DoreplacedentElement.SelectSingleNode("PropertyGroup/replacedemblyName");
            if (rootNamespaceElement != null)
                return rootNamespaceElement.InnerText;

            return projectName;
        }

19 Source : ProjectTestContext.cs
with MIT License
from dragonglasscom

public void SetreplacedemblyNameInProject(string rootNamespace)
        {
            var projectDoc = new XmlDoreplacedent();
            projectDoc.Load(ProjectFilePath);
            var propertyGroupElement = projectDoc.DoreplacedentElement.SelectSingleNode("PropertyGroup");
            var replacedemblyNameElement = propertyGroupElement.SelectSingleNode("replacedemblyName");
            if (replacedemblyNameElement == null)
            {
                replacedemblyNameElement = projectDoc.CreateElement("replacedemblyName");
                propertyGroupElement.AppendChild(replacedemblyNameElement);
            }

            replacedemblyNameElement.InnerText = rootNamespace;
            projectDoc.Save(ProjectFilePath);
        }

19 Source : MSBuildProjectEditor.cs
with MIT License
from Drizin

public void AddItem(string itemPath, BuildActionType itemType = BuildActionType.Compile, string parenreplacedemPath = null)
        {
            XmlNode itemGroup = null;
            itemPath = new Uri(this._projectFileFullPath).MakeRelativeUri(new Uri(new FileInfo(itemPath).FullName)).ToString().Replace("/", "\\");
            if (parenreplacedemPath != null)
                parenreplacedemPath = new Uri(this._projectFileFullPath).MakeRelativeUri(new Uri(new FileInfo(parenreplacedemPath).FullName)).ToString().Replace("/", "\\");

            if (parenreplacedemPath != null && _projectType == ProjectType.NonSDKStyle)
            {
                // ensure parent file is in msbuild project
                XmlNode parentNode = _doc.SelectSingleNode("//*[@Include='" + parenreplacedemPath + "'][local-name()='None' or local-name()='Compile']");
                if (_projectType == ProjectType.NonSDKStyle && parentNode == null)
                    throw new Exception($"Parent item not found in project file {this._projectFileFullPath}");
                itemGroup = parentNode.ParentNode;
            }

            if (itemGroup == null)
                itemGroup = _doc.SelectSingleNode("//msbuild:ItemGroup", _nsmgr);
            if (itemGroup == null)
            {
                XmlNode project = _doc.SelectSingleNode("//msbuild:Project", _nsmgr);
                itemGroup = _doc.CreateElement("ItemGroup", _doc.DoreplacedentElement.NamespaceURI);
                project.AppendChild(itemGroup);
            }


            if (parenreplacedemPath != null)
            {
                if (!_addedDependenreplacedems.ContainsKey(parenreplacedemPath))
                    _addedDependenreplacedems[parenreplacedemPath] = new List<string>();
                _addedDependenreplacedems[parenreplacedemPath].Add(itemPath);
            }
            else
            {
                if (!_addedDependenreplacedems.ContainsKey(itemPath))
                    _addedIndependenreplacedems.Add(itemPath);
            }


            if (_projectType == ProjectType.SDKStyle)
            {
                //TODO: double check that file is under csproj folder? if it's not under we have to include!
            }

            // Checking the netcore "Compile Remove" nodes.
            if (_projectType == ProjectType.SDKStyle)
            {
                XmlNode compileRemoveNode = _doc.SelectSingleNode("//msbuild:Compile[@Remove='" + itemPath + "']", _nsmgr);

                // Compiled files shouldn't have a "Compile Remove" node. "None" files should.
                if (itemType == BuildActionType.Compile)
                {
                    if (compileRemoveNode != null)
                        compileRemoveNode.ParentNode.RemoveChild(compileRemoveNode);
                }
                else
                {
                    if (compileRemoveNode == null)
                    {
                        XmlElement newCompileRemoveNode = _doc.CreateElement("Compile", _doc.DoreplacedentElement.NamespaceURI);
                        newCompileRemoveNode.SetAttribute("Remove", itemPath);
                        itemGroup.AppendChild(newCompileRemoveNode); //TODO: does this need to be before the "None Update" node?
                    }
                }
            }

            // Checking the "None/Compile" nodes
            //XmlNode existingElement = _doc.SelectSingleNode("//*[local-name()='None' or local-name()='Compile'][@" + ((IsCore && itemType == OutputFileType.Compile) ? "Update" : "Include") + "='" + itemPath + "']", _nsmgr);
            XmlElement existingElement = (XmlElement)_doc.SelectSingleNode("//*[local-name()='None' or local-name()='Compile'][@Include='" + itemPath + "' or @Update='" + itemPath + "']", _nsmgr);
            if (existingElement != null)
            {
                // node exists in csproj but shouldn't be there
                if (itemType == BuildActionType.NonProjecreplacedem)
                { existingElement.ParentNode.RemoveChild(existingElement); existingElement = null; }

                // node exists but wrong type
                if (_projectType == ProjectType.NonSDKStyle && itemType.ToString() != existingElement.Name)
                { existingElement.ParentNode.RemoveChild(existingElement); existingElement = null; }

                // node exists but wrong type
                if (_projectType == ProjectType.NonSDKStyle && itemType.ToString() != existingElement.Name)
                { existingElement.ParentNode.RemoveChild(existingElement); existingElement = null; }

                // node exists but is not necessary
                if (_projectType == ProjectType.SDKStyle && itemType == BuildActionType.Compile && parenreplacedemPath == null)
                { existingElement.ParentNode.RemoveChild(existingElement); existingElement = null; }

                //// node exists shouldn't be there
                //if (IsCore && itemType == OutputFileType.Compile && parenreplacedemPath != null 
                //    && existingElement.SelectSingleNode("[msbuild:DependentUpon/text()='" + parenreplacedemPath + "'][@" + ((IsCore && itemType == OutputFileType.Compile) ? "Update" : "Include") + "='" + itemPath + "']", _nsmgr) != null)
                //{ existingElement.ParentNode.RemoveChild(existingElement); existingElement = null; }
                //_doc.SelectSingleNode("//msbuild:" + itemType.ToString() + 
            }

            if (itemType == BuildActionType.NonProjecreplacedem)
                return;
            // core projects don't need to declare regular compiled files
            if (existingElement == null && (_projectType == ProjectType.SDKStyle && itemType == BuildActionType.Compile) && parenreplacedemPath == null)
                return;

            string expectedType = "Include";
            if (_projectType == ProjectType.SDKStyle && itemType == BuildActionType.Compile)
                expectedType = "Update";

            if (existingElement != null)
            {
                if (existingElement.Attributes["Include"] != null && (expectedType != "Include" || existingElement.Attributes["Include"].Value != itemPath))
                    existingElement.Attributes.RemoveNamedItem("Include");
                if (existingElement.Attributes["Update"] != null && (expectedType != "Update" || existingElement.Attributes["Update"].Value != itemPath))
                    existingElement.Attributes.RemoveNamedItem("Update");
            }
            if (existingElement == null)
            {
                existingElement = _doc.CreateElement(itemType.ToString(), _doc.DoreplacedentElement.NamespaceURI);
                existingElement.SetAttribute(((_projectType == ProjectType.SDKStyle && itemType == BuildActionType.Compile) ? "Update" : "Include"), itemPath);
            }
            if (existingElement.Attributes["Include"] == null && expectedType == "Include")
                existingElement.SetAttribute("Include", itemPath);
            if (existingElement.Attributes["Update"] == null && expectedType == "Update")
                existingElement.SetAttribute("Update", itemPath);


            if (parenreplacedemPath != null)
            {
                if (existingElement.SelectSingleNode("//msbuild:DependentUpon[text()='" + parenreplacedemPath + "']", _nsmgr) == null)
                {
                    var nodes = existingElement.SelectNodes("//msbuild:DependentUpon", _nsmgr);
                    for (int i = 0; i < nodes.Count; i++)
                        nodes.Item(i).ParentNode.RemoveChild(nodes.Item(i));

                    XmlElement dependentUpon = _doc.CreateElement("DependentUpon", _doc.DoreplacedentElement.NamespaceURI);
                    dependentUpon.InnerText = parenreplacedemPath;
                    existingElement.AppendChild(dependentUpon);
                }
            }

            if (existingElement.ParentNode == null) // new elements
                itemGroup.AppendChild(existingElement);
        }

19 Source : MSBuildProjectEditor.cs
with MIT License
from Drizin

public void RemoveUnusedDependenreplacedems(string parenreplacedemPath)
        {
            parenreplacedemPath = new Uri(this._projectFileFullPath).MakeRelativeUri(new Uri(new FileInfo(parenreplacedemPath).FullName)).ToString().Replace("/", "\\");
            XmlNode parentNode = _doc.SelectSingleNode("//*[@Include='" + parenreplacedemPath + "'][local-name()='None' or local-name()='Compile']");
            if (_projectType == ProjectType.NonSDKStyle && parentNode == null)
                throw new Exception($"Parent item not found in project file {this._projectFileFullPath}");

            XmlNodeList children = _doc.SelectNodes("//msbuild:*[msbuild:DependentUpon/text()='" + parenreplacedemPath + "'][local-name()='None' or local-name()='Compile']", _nsmgr);
            for (int i = 0; i < children.Count; i++)
            {
                string itemName = children.Item(i).Attributes["Include"].Value;
                if (!_addedDependenreplacedems[parenreplacedemPath].Contains(itemName))
                    children.Item(i).ParentNode.RemoveChild(children.Item(i));
            }
        }

19 Source : Initializer.cs
with GNU General Public License v3.0
from DSorlov

private void Init_PersistedData(string pathName)
        {
            try
            {
                WriteProgress("Restoring data..", 50);
                string configFile = System.IO.Path.Combine(pathName, "Sorlov.PowerShell.PersistedState.xml");
                if (System.IO.File.Exists(configFile))
                {
                    WriteProgress("Loading persisted state..", 55);
                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
                    xmlDoc.Load(configFile);

                    try
                    {
                        if (LibraryConfiguration.IsNotNull("PersistPath"))
                            if (LibraryConfiguration.IsTrue("PersistPath"))
                            {
                                WriteProgress("Processing general items..", 60);
                                XmlNode pwdNode = xmlDoc.SelectSingleNode("/PSState/General/Pwd");
                                InvokeScript(string.Format("Set-Location \"{0}\"", pwdNode.Attributes["Value"].Value));
                            }
                    }
                    catch (Exception ex)
                    {
                        WriteWarning(string.Format("Could not process PersistPath, error: {0}", ex.Message));
                    }

                    try
                    {
                        if (LibraryConfiguration.IsNotNull("PersistHistory"))
                            if (LibraryConfiguration.IsTrue("PersistHistory"))
                            {
                                WriteProgress("Restoring history..", 65);
                                int id = 0;
                                string historyFile = "@'" + Environment.NewLine;
                                historyFile += "#TYPE Microsoft.PowerShell.Commands.HistoryInfo" + Environment.NewLine;
                                historyFile += "\"Id\",\"CommandLine\",\"ExecutionStatus\",\"StartExecutionTime\",\"EndExecutionTime\"" + Environment.NewLine;
                                XmlNodeList history = xmlDoc.SelectNodes("/PSState/HistoryList/History");
                                foreach (XmlNode historyNode in history)
                                {
                                    historyFile += string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"" + Environment.NewLine, historyNode.Attributes["Id"].Value, historyNode.Attributes["CommandLine"].Value, historyNode.Attributes["ExecutionStatus"].Value, historyNode.Attributes["StartExecutionTime"].Value, historyNode.Attributes["EndExecutionTime"].Value);
                                    id++;
                                }
                                historyFile += "'@ | ConvertFrom-CSV | Add-History";
                                InvokeScript(historyFile);
                            }
                    }
                    catch (Exception ex)
                    {
                        WriteWarning(string.Format("Could not process PersistHistory, error: {0}", ex.Message));
                    }

                    try
                    {
                        if (LibraryConfiguration.IsNotNull("PersistAliases"))
                            if (LibraryConfiguration.IsTrue("PersistAliases"))
                            {
                                WriteProgress("Restoring Aliases..", 75);
                                XmlNodeList aliases = xmlDoc.SelectNodes("/PSState/AliasList/Alias");
                                foreach (XmlNode alias in aliases)
                                    InvokeScript(string.Format("Set-Alias -Name {0} -Value {1} -Scope Global -Force -ErrorAction SilentlyContinue", alias.Attributes["Name"].Value, alias.Attributes["Definition"].Value));
                            }
                    }
                    catch (Exception ex)
                    {
                        WriteWarning(string.Format("Could not process PersistAliases, error: {0}", ex.Message));
                    }

                }
            }
            catch (Exception ex)
            {
                WriteWarning(string.Format("Could not process StateRestore, error: {0}", ex.Message));
            }
            
        }

19 Source : WorkspaceTree.xaml.cs
with MIT License
from DST-Tools

private TreeViewItem RenderV2(FileNode files, TreeView container)
		{
			WorkspaceFolderItem item;

			//workshop mods
			if(files.Name.StartsWith("workshop-"))
			{
				item = new WorkshopItem(files);
			}
			else
			{
				//initalize as a normal mod.
				item = new WorkspaceFolderItem(files);
			}

			if(files.Hreplacedubdirectories())
			{
				foreach (FileNode dir in files.Subdirectories)
				{
					if (!(this.RenderV2(dir, null) is WorkspaceFolderItem root)) continue;
					root.FontWeight = FontWeights.Normal;

					if (container != null)
					{
						container.Items.Add(root);
					}
					else
					{
						item.Items.Add(root);
					}
				}
			}

			if(files.HasFiles())
			{
				List<string> skiplist = new List<string>(20);
				foreach (FileInfo file in files.Files)
				{
					/* skip these files which added into skiplist, include bundled ktex(2019/5/30)
					 * put this first to avoid object construction
					 * this is the first check.
					 */
					if (skiplist.Contains(file.FullName)) continue;

					WorkspaceFileItem entry;

					//modinfo
					if(file.Name == "modinfo.lua")
					{
						//build
						entry = new ModInfoItem(file.FullName) { Header = "ModInfo" };
						item.Items.Add(entry);
						//skip other steps
						continue;
					}

					//texture bundle, read XML atlas first
					if (string.Compare(Path.GetExtension(file.Name), ".xml", true) == 0)
					{
						XmlDoreplacedent ktex_atlas = new XmlDoreplacedent();

						try
						{
							//create a bundle item
							entry = new TextureItem(file.FullName) { Header = Path.GetFileNameWithoutExtension(file.FullName) };
							ktex_atlas.Load(file.FullName);

							//read XML atlas to find out all the textures
							var textures = ktex_atlas.SelectSingleNode("Atlas")?.SelectNodes("Texture");
							if (textures != null) 
								foreach (XmlNode texture in textures)
								{
									//iterate attributes to find an attribute named "filename"
									foreach (XmlAttribute att in texture.Attributes)
									{
										if (att.LocalName != "filename")
											continue;
										string ktex_path = Path.Combine(file.DirectoryName, att.Value);
										//add it's path into skip list
										skiplist.Add(ktex_path);
										//build bundle, this is the texture step.
										WorkspaceFileItem ktex = new WorkspaceFileItem(ktex_path) { Header = att.Value };
										entry.Items.Add(ktex);
									}
								}

							//add XML itself into the bundle
							{
								WorkspaceFileItem xml_atlas = new WorkspaceFileItem(file.FullName);
								entry.Items.Add(xml_atlas);
							}

							//set bundle mouse event handling
							entry.MouseRightButtonDown += new MouseButtonEventHandler(delegate (object sender, MouseButtonEventArgs e)
							{
								Logger.Info("ContextMenu: " + file.FullName);
							});
							entry.PreviewMouseDown += new MouseButtonEventHandler(delegate (object sender, MouseButtonEventArgs e)
							{
								// @ToDo open Texture-Editor
								Logger.Info("Texture-Editor: " + file.FullName);
								//this.GetCore.Workspace.OpenDoreplacedent(file.FullName);
							});

							//remove these existed texture items
							{
								List<TreeViewItem> excludes = new List<TreeViewItem>(4);
								//find these items to remove by foreach,and add them into excludes
								foreach (TreeViewItem to_check in item.Items)
								{
									if (skiplist.Contains((to_check as WorkspaceFileItem)?.FullPath))
										excludes.Add(to_check);
								}
								foreach (object to_remove in excludes)
								{
									//remove it now because I can't do so when enumerating item.Items
									//or a InvalidOpreationException will be thrown.
									item.Items.Remove(to_remove);
								}
							}
						}
						catch (System.Xml.XPath.XPathException)
						{
							//use continue to avoid a wrong bundle being added into the tree by skipping the code above
							continue;
						}
						catch(XmlException)
						{
							//skip if the xml file does not contain any texture info
							continue;
						}
						catch(Exception e)
						{
							Console.WriteLine(e.Message);
							Console.WriteLine(e.StackTrace);
							//same as before
							continue;
						}


						item.Items.Add(entry);
						//skip other steps to make it faster
						continue;
					}

					//other files
					{
						entry = new WorkspaceFileItem(file.FullName)
						{
							Header = file.Name
						};
						item.Items.Add(entry);
					}
				}
			}

			return item;
		}

19 Source : SettingService.cs
with Apache License 2.0
from duyanming

private static string AppSetting(string key)
        {
            XmlDoreplacedent doc = GetXmlDoreplacedent();
            XmlNode appset = doc.SelectSingleNode($"//appSettings/add[@key='{key}']");
            return appset == null ? string.Empty : appset.Attributes["value"].Value;
        }

19 Source : SettingService.cs
with Apache License 2.0
from duyanming

private static string NodeText(string key)
        {
            XmlDoreplacedent doc = GetXmlDoreplacedent();
            string appset = doc.SelectSingleNode($"//{key}")?.InnerText;
            return appset ?? string.Empty;
        }

19 Source : SettingService.cs
with Apache License 2.0
from duyanming

public static void InitConfig()
        {
            #region 配置初始化
            XmlDoreplacedent xml = GetXmlDoreplacedent();
            XmlNode local = xml.SelectSingleNode("//Port");
            Local.Port = Convert.ToInt32(NodeText("Port"));
            //Local.IpAddress = local.Attributes["Ip"].Value;
            Weight = Convert.ToInt32(NodeText("Weight"));
            AppName = NodeText("AppName");
            FuncName = NodeText("FuncName");
            if (long.TryParse(NodeText("TimeOut"), out long timeOut))
            {
                TimeOut = timeOut;
            }
            else
            {
                TimeOut = 10000;
            }
            XmlNodeList _Ts = xml.SelectNodes("//Ts");
            #region 需要忽略的 插件
            var ignoreFunc = NodeText("IgnoreFuncName");
            ignoreFunc.Split(',').ToList().ForEach(item =>
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    IgnoreFuncNames.Add(item.ToUpper());
                }
            });
            #endregion
            foreach (XmlNode ts in _Ts)
            {
                Target target = new Target
                {
                    IpAddress = ts.Attributes["Ip"].Value,
                    Port = Convert.ToInt32(ts.Attributes["Port"].Value)
                };
                Ts.Add(target);
            }
            //通过Anno.config 初始化AppSettings
            InitConstAppSettings(xml);
            //根据  SettingService.FuncName 加载服务集合
            replacedemblys.Initreplacedembly();
            replacedemblys.AddPlugsreplacedembly();

            CustomConfiguration.InitConst(xml);
            #endregion

            #region 初始化 ID生成器

            var idWorker = NodeText("IdWorker");
            if (!string.IsNullOrWhiteSpace(idWorker))
            {
                var wd = idWorker.Split(',');
                if (wd.Length == 2)
                {
                    long.TryParse(wd[0], out long worker);
                    long.TryParse(wd[1], out long datacenter);
                    WorkerId = worker;
                    DatacenterId = datacenter;
                }
            }
            #endregion
        }

19 Source : ThriftConfig.cs
with Apache License 2.0
from duyanming

private bool Save()
        {
            try
            {
                XmlDoreplacedent xml = new XmlDoreplacedent();
                xml.Load(Path.Combine(Directory.GetCurrentDirectory(), AnnoFile));
                XmlNode servers = xml.SelectSingleNode("//configuration/Servers");//查找<Servers> 
                servers.RemoveAll();
                List<ServiceInfo> tempIps = new List<ServiceInfo>();
                ServiceInfoList.ForEach(p =>
                {
                    if (tempIps.FindAll(t => p.Ip == t.Ip && p.Port == t.Port).Count <= 0)
                    {
                        tempIps.Add(p);
                    }
                });
                tempIps.ForEach(p =>
                {
                    XmlElement xe = xml.CreateElement("dc");
                    xe.SetAttribute("name", p.Name);
                    xe.SetAttribute("nickname", p.NickName);
                    xe.SetAttribute("ip", p.Ip);
                    xe.SetAttribute("port", p.Port.ToString());
                    xe.SetAttribute("timeout", p.Timeout.ToString());
                    xe.SetAttribute("weight", p.Weight.ToString());
                    servers.AppendChild(xe);
                });
                xml.Save(Path.Combine(Directory.GetCurrentDirectory(), AnnoFile));
            }
            catch (Exception ex)
            {
                Log.Anno(ex, typeof(ThriftConfig));
                return false;
            }
            return true;
        }

19 Source : SettingService.cs
with Apache License 2.0
from duyanming

public static void InitConst(XmlDoreplacedent doc)
        {
            XmlNode appSettings = doc.SelectSingleNode("//appSettings");
            if (appSettings == null || appSettings.ChildNodes.Count <= 0)
            {
                return;
            }

            foreach (XmlNode node in appSettings.ChildNodes)
            {
                try
                {
                    if (node.Attributes != null)
                    {
                        string key = node.Attributes["key"].Value;
                        if (!string.IsNullOrWhiteSpace(key) && settings.ContainsKey(key) == false)
                        {
                            string value = node.Attributes["value"].Value;
                            settings.Add(key, value);
                        }
                    }
                }
                catch
                {
                    //
                }
            }
        }

19 Source : XmlHelper.cs
with MIT License
from duyanming

public XmlNode GetNodes(string xmlPath, string nodename)
        {
            XmlDoreplacedent xml = new XmlDoreplacedent();
            xml.Load(xmlPath);
            XmlNode nodes = xml.SelectSingleNode(nodename);
            return nodes;
        }

See More Examples