我正在尝试更深入地了解 LINQ-to-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
-attribute,查询该文档就可以正常工作.当我重新添加它时,查询返回 null 并且什么也没有.我试图自己找出答案,但我还没有找到可以解决我的问题的解决方案.
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");
这篇关于将 xmlns 属性添加到我的 XML 文档中的根元素时,我的 linq 查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!