【问题标题】:Linq: Elements not working when I have a namespace in XML fileLinq:当我在 XML 文件中有命名空间时,元素不起作用
【发布时间】:2014-04-10 16:06:13
【问题描述】:

我发现了一些使用 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> 

任何帮助将不胜感激,谢谢。

【问题讨论】:

标签: c# linq linq-to-xml


【解决方案1】:

您还需要使用元素名称指定命名空间:

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

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

【讨论】:

  • 非常感谢。我用这个: var usernames = from r in doc.Descendants(ns + "Credential") select r.Element(ns + "Username").Value;当我将 ns 添加到我的时,它仍然由于某种“奇怪”的原因而拒绝工作。当我改用这个 select 语句时,它开始工作了。
【解决方案2】:

您就快到了,您只需在查询中包含每个元素的命名空间标识符。稍作调整后,您的代码就可以工作了:

var usernames = from r in doc.Descendants(ns + "Credential")
                select r.Element(ns + "Username").Value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多