c# - 将 xmlns 属性添加到我的 XML 文档中的根元素时,我的 linq 查询不起作用

标签 c# xml linq namespaces

我正在尝试更深入地了解 LINQ-to-XML,因此我为自己制作了一个简洁的 XML 文档小示例来进行尝试。此外,我尝试(并成功地)为该文件制作了我自己的 XML 模式,只是为了测试一下。 XML 文档非常简单,看起来像这样:

<cars xmlns="/carsSchema.xsd">
  <car age="5">
    <carId>1</carId>
    <brand>BMW</brand>
    <model>320i</model>
    <color paintType="metallic">Red</color>
  </car>

  <car age="2">
    <carId>2</carId>
    <brand>VW</brand>
    <model>Golf</model>
    <color paintType="matt">White</color>
  </car>
[...]
</cars>

现在,如果我从根元素中删除 xmlns 属性,查询此文档就可以正常工作。当我重新添加它时,查询返回 null,什么也没有。我试图自己找出答案,但我还没有找到解决我的问题的解决方案。

这是 C# 位:

        XDocument xmlDoc = XDocument.Load(currentDir + "\\Cars.xml");

// XNamespace ns = "{" + currentDir + "\\carSchema.xsd}";
// Tried to query xmlDoc.Descendants(ns+"car") after reading another post, 
// but that  made no difference

        var carInfo1 = from car in xmlDoc.Descendants("car")
                       select (string)car.Element("brand") + ": " + (string)car.Element("model");

有没有人看出哪里出了问题?为什么 LINQ 应该真正关心命名空间?它不能只查询我的文件而不关心它吗?

提前致谢! :-)

最佳答案

当您按后代和元素进行搜索时,您需要指定命名空间。使用 LINQ to XML 这非常容易。看起来你快到了,但没有为元素做到这一点:

XDocument xmlDoc = XDocument.Load(currentDir + "\\Cars.xml");
// I don't think namespace URIs are really resolved. I'm not sure though -
// for a proof of concept, I suggest you use a namespace of
// http://dummy.com/dummy.xsd
XNamespace ns = "/carSchema.xsd";

var carInfo1 = from car in xmlDoc.Descendants(ns + "car")
                   select (string)car.Element(ns + "brand") + ": " + 
                          (string)car.Element(ns + "model");

关于c# - 将 xmlns 属性添加到我的 XML 文档中的根元素时,我的 linq 查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/793580/

相关文章:

c# - MVC 3 - 在我的 'Views' 上创建搜索的最佳方法

iphone - 如果标签名称未知,如何在iPhone中以nsdictionary格式转换xml文件

xml - 为什么对 XML 同时使用 XSD 和 DTD?

c# - linq to sql + 更新表

c# - 动态 linq :Creating an extension method that produces JSON result

c# - 为什么不能将 OUT 泛型修饰符应用于类和接口(interface)?

c# - DataGridView 清除并重新获得焦点

c# - 在不同的 .NET 框架之间共享记录器

java - XJC : Creating Stub for XBRL schemas

c# - 使用 LINQ 表达式的文本表示