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

我正在尝试更多地使用LINQ-to-XML,所以我自己做了一个简洁的小例子XML文档来尝试。 另外,我尝试(并且成功地)为该文件创建了自己的XML模式,只是为了测试。 XML文档非常简单,几乎看起来像这样:

  1 BMW 320i Red   2 VW Golf White  [...]  

现在,如果我从根元素中删除xmlns -attribute,查询此文档就可以了。 当我重新添加它时,查询返回null,什么也没有。 我试图自己找出来,但我还没有找到解决问题的解决办法。

这是C#-bit:

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

当您使用虚构的“http://”URI作为命名空间时,这也适用。 你是对的。 它没有得到解决。

  private XNamespace ns = "http://schemas.xin2009.com/DataMap/2009"; IEnumerable names = (from spnode in _map.Descendants(ns + "Entity") where spnode.Attribute("name").Value == this.Entity select spnode.Element(ns + "StoredProcedure").Attribute("name").Value); 

请注意,只需将命名空间的ns添加到元素而不是属性。