Linq: Elements not working when I have a namespace in XML file

社会主义新天地 提交于 2021-01-28 06:45:44

问题


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.


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/22993286/linq-elements-not-working-when-i-have-a-namespace-in-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!