문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top