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

Using LINQ to XML to get a list of element values is not working

I have a XML file with data like:

<?xml version="1.0" encoding="utf-8"?>
<PublisherDatabase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="4" xmlns="http://www.publictalksoftware.co.uk/msa">
  <Publishers>
    <Publisher>
      <Name>Mr Happy</Name>
    </Publisher>
    <Publisher>
      <Name>Mr Sad</Name>
    </Publisher>
  </Publishers>
</PublisherDatabase>

That is a snippet, reduced to bare bones.

Now, I am trying to use LINQ to XML to get a List<string> of all the Name values.

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

This returns a list of 0 items:

XDocument xmlDoc = XDocument.Load(publisherDataPath);
var list = xmlDoc.Root.Elements("Publishers").Elements("Name")
                              .Select(element => element.Value)
                              .ToList();
Console.WriteLine(list.ToString());

What is my mistake? Then I tried:

var list = xmlDoc.Root.Elements("Publishers").Elements("Publisher").Elements("Name")
       .Select(element => element.Value)
       .ToList();
Console.WriteLine(list.ToString());

Still ends up with 0.

>Solution :

Those xml elements belong to the http://www.publictalksoftware.co.uk/msa xml namespace.

You have to specify that one in your LINQ query for each element.

XNamespace ns = "http://www.publictalksoftware.co.uk/msa";
var list = xmlDoc.Root.Elements(ns + "Publishers").Elements(ns + "Publisher").Elements(ns + "Name")
    .Select(element => element.Value)
    .ToList();
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