Linq:当我在XML文件中有名称空间时,元素不起作用 [英] Linq: Elements not working when I have a namespace in XML file

查看:24
本文介绍了Linq:当我在XML文件中有名称空间时,元素不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些使用xml到linq解析器的示例stackoverflow.我的xml有一个名称空间,所以我也尝试设置该名称空间(尽管我认为您可以从文件的a中读取它)?

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?)

无论如何,当我运行c#/linq代码时,它无法识别xml中的元素.除非我从xml文件中删除xmlns标记.

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");

我还建议您使用显式强制转换,而不要使用 Value 属性,以防止可能的异常.

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

这篇关于Linq:当我在XML文件中有名称空间时,元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆