Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update custom format XML file using C#?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
 
 
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading