Convert file to XML and maintain attribute names

2

I am using C # , and I need to convert an XML list to an array so that it can be sent via WCF and that data can be displayed in the web client.

Of the following arrangement I just need to keep Name and Url .

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
  <Cameras>
   <Camera Name="Camera1" Url="Camera1" Width="600" Height="800" />
   <Camera Name="Camera2" Url="Camera2" Width="600" Height="800" />
</Cameras>
</Configuration>

I was dealing with this code ...

XmlDocument xml = new XmlDocument();
xml.Load(
    Path.Combine(
        Path.GetDirectoryName(
            typeof(ConfigListenerSecondary).Assembly.Location
        ), configFile
    )
);
XmlNodeList xnList = xml.SelectNodes("//Camera");
foreach (XmlNode xn in xnList)
{
    string Name = xn["Name"].InnerText;
    string Url = xn["Url"].InnerText;
    Console.WriteLine(Name, Url);
}

... but it displays the following error:

  

System.NullReferenceException: 'Object reference not set to an instance of an object.'

    
asked by Javier Luna 02.01.2018 в 21:30
source

1 answer

2

When you do:

xn["Name"]

or

xn["Url"]

... you are looking for a child node with those names. This is not what you want. In your case, what you want is to read the attributes Name and Url .

This is the correct way to do it:

XmlNodeList xnList = xml.SelectNodes("//Camera");
foreach (XmlElement ele in xnList)
{
    string Name = ele.GetAttribute("Name");
    string Url = ele.GetAttribute("Url");
    Console.WriteLine($"{Name}, {Url}");
}
    
answered by 02.01.2018 / 21:38
source