Home > Mobile >  Cannot parse xml to List<> C#
Cannot parse xml to List<> C#

Time:11-15

I have this xml:

<NewDataSet xmlns="http://anonymous_link_here">
    <Table>
        <Name>Example</Name>
    </Table>
    <Table>
        <Name>Example</Name>
    </Table>
    <Table>
        <Name>Example</Name>
    </Table>
    <Table>
        <Name>Example</Name>
    </Table>
</NewDataSet>

I'm trying to parse this xml to a List<myClass>:

        public static List<myClass> ConvertToList(string xml)
        {
            var objects= XDocument.Parse(xml);
            var objectsList= (from o in objects.Root.Elements()
                               select new myClass()
                               {
                                   Name = (string)o.Element("Name"),
                               }).ToList();
            return objectsList;
        }

myClass class:

[Serializable]
[XmlRoot("Table"), Namespace="http://anonymous_link_here"]

public class myClass{

    [XmlElement(ElementName="Name"), Namespace="http://anonymous_link_here"]
    public string Name { get; set; }

}

I don't know why I get the right count of elements in the objectsList, but the Name properties are null. I think there is something wrong with: Name = (string)o.Element("Name"). Any help would be appreciated.

CodePudding user response:

The problem is that your call to o.Element("Name") looks for an element called Name without a namespace, whereas your elements are in the default namespace for the document, which is "http://anonymous_link_here".

Fortunately, LINQ to XML makes it easy to fix that using XNamespace:

XNamespace ns = "http://anonymous_link_here";
XElement child = parent.Element(ns   "Name");

With a bit of rewriting (and renaming to avoid myClass), this is how your method would look:

public static List<Table> ConvertToList(string xml)
{
    var document = XDocument.Parse(xml);
    XNamespace ns = "http://anonymous_link_here";
    return document.Root
        .Elements()
        .Select(element => new Table { Name = (string) element.Element(ns   "Name") })
        .ToList();
}

Or in an expression-bodied method:

private static readonly XNamespace TableNamespace = "http://anonymous_link_here";

public static List<Table> ConvertToList(string xml) =>
    XDocument.Parse(xml)
        .Root
        .Elements()
        .Select(element => new Table 
        { 
            Name = (string) element.Element(TableNamespace   "Name") 
        })
        .ToList();

CodePudding user response:

You can also try the code below; notice Name = o.Value not .Element,

public static List<myClass> ConvertToList(string xml)
{
     var objects = XDocument.Parse(xml);
     var objectsList = (from o in objects.Root.Elements()
                           select new myClass()
                           {
                               Name = o.Value,
                           }).ToList();
      return objectsList;
 }
  • Related