Question

I found some examples stackoverflow of using a xml to linq parser. My xml has a namespace, so I tried setting that as well (though I would of thought you could read that in a from the file?)

Anyway, when I run the c#/linq code it does not recognise the elements in the xml. Unless I remove the xmlns tag from the xml file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            XDocument document = XDocument.Load("C:\\NewCredential.xml");    
            XNamespace ns = "http://myworld.org/CredCentral.xsd";
            var usernames = from r in document.Descendants(ns + "Credential")
                             select r.Element("Username").Value;

            foreach (var r in usernames)
            {
                Console.WriteLine(r.ToString());
            }
            Console.ReadLine();

        }
    }    
}    



<?xml version="1.0" encoding="utf-8" ?>
<CredCentral xmlns="http://myworld.org/CredCentral.xsd">
  <Credential>
    <CredentialId>123456789</CredentialId>    
    <Username>johnsmith</Username>
    <Password>password</Password>
  </Credential>
</CredCentral> 

Any help would be appreciated, thank you kindly.

Was it helpful?

Solution

You need to specify the namespace with element name as well:

from r in document.Descendants(ns + "Credential")
select (string)r.Element(ns + "Username");

Also I recommend you use an explicit cast instead of using Value property that will prevent the possible exceptions.

OTHER TIPS

You're almost there, you just have to include the namespace identifier for every element in your query. With this slight adjustment, your code works:

var usernames = from r in doc.Descendants(ns + "Credential")
                select r.Element(ns + "Username").Value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top