I have an XML file which was created by one of my other application in a custom format. Which looks like below and now I want to update FilePath value to different path. I want to update the value based on the key FilePath
. I tried different logics in C# but it is always returning Key as null
.
<?xml version="1.0" standalone="yes"?>
<Root>
<Configuration>
<Key>FilePath</Key>
<Value>C:\UserData.xlsx</Value>
</Configuration>
<Configuration>
<Key>FileSize</Key>
<Value>1024</Value>
</Configuration>
<Configuration>
<Key>SourceMachine</Key>
<Value>17HRDPQSt</Value>
</Configuration>
</Root>
C# Code:
XmlDocument doc = new XmlDocument();
doc.Load(xmlpath);
XmlNodeList aNodes = doc.SelectNodes("/Root/Configuration");
foreach (XmlNode aNode in aNodes)
{
XmlAttribute idAttribute = aNode.Attributes["FilePath"];
if (idAttribute != null)
{
string newValue = excelFilePath;
if (string.IsNullOrEmpty(newValue))
{
idAttribute.Value = excelFilePath;
}
}
}
doc.Save(xmlpath);
How can I update the FilePath value?
CodePudding user response:
Using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication17
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement filePath = doc.Descendants("Configuration").Where(x => (string)x.Element("Key") == "FilePath").FirstOrDefault();
filePath.SetElementValue("Value", "New File Path");
}
}
}