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