Search code examples
c#xmlxmlreaderreadxml

Reading the XML with namespaces at attribute level using c#


I have an XML file like following

<?xml version="1.0"?>
<appSettings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <add xdt:Transform="Replace" xdt:Locator="Match(key)" key="Key1" value="TransformValue1"/>
  <add xdt:Transform="Replace" xdt:Locator="Match(key)" key="Key2" value="TransformValue2"/>
  <add xdt:Transform="Replace" xdt:Locator="Match(key)" key="Key3" value="TransformValue3"/>
  <add xdt:Transform="Replace" xdt:Locator="Match(key)" key="Key4" value="TransformValue4"/>

  <add xdt:Transform="Insert" key="Key6" value="TransformValue6"/>
</appSettings>

I want to get this XML as List of class Key. here the Key class is as follows

[Serializable]
public class Key
{
    public string Key { get; set; }
    public string Value { get; set; }
    public string Transform { get; set; }
    public string Locator { get; set; }
}

Please suggest

Hi all, for better understanding of my problem i'm updating the question with purpose.

Purpose: As part of automatic deployments, we are planning to automate the deployment of web.config file also. To achieve this process we are using the concept of "Web config transform". To achieve this "Web config transform", we will maintain the transform files(for all instances and clients) in centralized server and these will be used for transform. But to update the transform file we are giving the Ui for the deployment team member. For this we need to read the XML config with name spaces.


Solution

  • If you create models to hold your data, then you can easily deserialize object from file with 2 lines of code:

    public class appSettings
    {
        [XmlElement("add")]
        public List<Item> AddItems { get; set; }
    }
    
    public class Item
    {
        [XmlAttribute("key")]
        public string Key { get; set; }
        [XmlAttribute("value")]
        public string Value { get; set; }
        [XmlAttribute(Namespace="http://schemas.microsoft.com/XML-Document-Transform")]
        public string Transform { get; set; }
        [XmlAttribute(Namespace="http://schemas.microsoft.com/XML-Document-Transform")]
        public string Locator { get; set; }
    }
    
    XmlSerializer ser = new XmlSerializer(typeof(appSettings));
    var settings = (appSettings)ser.Deserialize(File.Open("test.xml", FileMode.Open));
    settings.AddItems; //<- there is your list