我的XML文档中添加的xmlns属性的根元素时,我的LINQ查询不工作 [英] My linq-query doesn't work when adding the xmlns-attribute to the root-element in my XML-document

查看:210
本文介绍了我的XML文档中添加的xmlns属性的根元素时,我的LINQ查询不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得更多的进入LINQ到XML的,所以我自己做了一个整洁的小示例XML文档尝试的事情。此外,我试图(和成功)做了我自己的XML-模式该文件,只是为了测试的事情了。该XML文档是非常简单的,和几乎看起来是这样的:

I'm trying to get more into LINQ-to-XML, so I've made myself a neat little example XML-document to try things out on. In addition, I tried (and successfully) made my own XML-schema for that file, just to test things out. The XML-document is pretty straightforward, and pretty much looks like this:

<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 <工作得很好/ code> -attribute从根元素。当我将其重新添加,查询返回null并没有什么。我一直试图通过自己找出来了,但我还没有找到能解决我的问题sollution

Now, querying this document works just fine if i remove the xmlns-attribute from the root element. When i add it back in, the query returns null and nothing. I've tried to find out by myself, but I've yet to find a sollution that fixes my problem.

下面是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真正关心的的许多关于命名空间?不能只是询问我的文件,不关心吗?

Anyone sees what's wrong? And why should LINQ really care that much about the namespace? Can't it just query my file and don't care about it?

谢谢! : - )

推荐答案

当你被后人和元素搜索,你需要指定的命名空间。这是相当容易的LINQ to XML。它看起来像你几乎存在,但针对的元素并没有做到这一点:

When you're searching by descendants and element, you need to specify the namespace. This is pretty easy with LINQ to XML. It looks like you were nearly there, but didn't do it for the elements:

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

这篇关于我的XML文档中添加的xmlns属性的根元素时,我的LINQ查询不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆