c# - Linq:当我在 XML 文件中有命名空间时,元素不起作用

标签 c# linq linq-to-xml

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

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

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> 

如有任何帮助,我们将不胜感激,谢谢。

最佳答案

您还需要指定带有元素名称的命名空间:

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

此外,我建议您使用显式强制转换而不是使用 Value 属性,这样可以防止可能出现的异常。

关于c# - Linq:当我在 XML 文件中有命名空间时,元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22993286/

相关文章:

c# - 父线程休眠时子线程也休眠?

c# - 在 Entity Framework 中为子列表加入 vs 导航属性

c# - linq插入: getting the row number

c# - 使用 C#,如何逐行显示 XML?

c# - 无法在可移植类库中使用 linq 查询找到 xml 元素

c# - Azure SDK 2.9 诊断异常

c# - 'await' 运算符只能在 Xamarin Android 中的异步方法中使用

c# - 在图形区域外向 ZedGraph 添加文本

c# - Integer 包含 linq c# 但使用 using 表达式

c# - 正则表达式问题匹配字符串模式“A-Za-z-A-Za-z_”