Problem in getting the node values of same node names from an xml to a list using linq RRS feed

  • Question

  • User483994611 posted

    Basically i want to get the node names from an xml to a list<> by linq It may be

    var list=new List<string>

    or in the form of List<User>

    i have the xml file like

    <?xml  version="1.0" encoding="utf-8"?>
    <RolePrev xmlns="http://schemas.microsoft.com">

    My Class is like

        public class User

            public User()

            public int ID { get; set; }
            public string Name { get; set; }
            [XmlArray(ElementName = "Previleges")]
            public List<string> Previleges { get; set; }
            [XmlElement(ElementName = "Role")]
            public string Role { get; set; }

    i want to deserialize it to List<User>

    string filepath = Server.MapPath("XML/RolePrev.xml");  

    User objUser = new User();
                XmlDocument xdoc = new XmlDocument();
                objUser.Role = xdoc.GetElementsByTagName("Role")[0].InnerText;
                objUser.Previleges = new List<string>();
                XmlNodeList list = xdoc.GetElementsByTagName("Previleges");
                for (int i = 0; i < list.Count; i++)

                    XmlElement Previleges = (XmlElement)xdoc.GetElementsByTagName("Previleges")[i];


    I want to use linq instead .please help me..like:-

     string filepath = Server.MapPath("XML/RolePrev.xml");   
                XDocument xdocument = XDocument.Load(filepath);
                var query = xdocument.Descendants("Previleges").ToList();

    query will return list of previleges....plz help


    Monday, January 7, 2013 2:13 PM

All replies

  • User1648350404 posted

    You can easily deserialize with XmlSerializer, have a look at following:


    Tuesday, January 8, 2013 6:28 AM
  • User483994611 posted

    I have found a way using linq

    XDocument xdocument = XDocument.Load(filepath);
                XNamespace nm = XNamespace.Get("http://schemas.microsoft.com");
                List<string> prev = xdocument.Descendants(nm + "Previleges")
                                       .Select(x => x.Value)
                objUser.Previleges = new List<string>();
                foreach (string str in prev)

    But is this the best way..using linq??

    Tuesday, January 8, 2013 2:03 PM