【发布时间】:2014-02-08 03:25:41
【问题描述】:
希望大家能帮帮我?
我有这个 XML 结构:
<DataBase
xsi:schemaLocation="http://somestuff.new/xml http://somestuff.xsd"
xmlns:ns3="http://somestuff.new/ns3"
xmlns:ns2="http://somestuff.new/ns2"
xmlns="http://somestuff.new/ns"
xmlns:xsi="http://somestuff.new/XMLScema-instance"
xmlns:ns4="http://somestuff.new/ns4">
<Cars>
<SmallCars attribute="Something">
<Id>licenceplate</Id>
<Parts attribute="All Parts">
<Extras>
<Gauges xmlns="http://somestuff.new/ns3">
<Speed>100</Speed>
<Rpm>3200</Rpm>
</Gauges>
</Extras>
</Parts>
</SmallCars>
</Cars>
</DataBase>
然后我创建了一个这样的汽车类:
public class Cars
{
public string CarType { get; set; }
public List<Parts> CarParts { get; set; }
}
还有一类零件:
public class Parts
{
public List<Gauges> CarExtras { get; set; }
}
最后但并非最不重要的一类仪表:
public class Gauges
{
public double Speed { get; set; }
public int Rpm { get; set; }
}
现在我想创建一个 LINQ 查询,从 XML 的 Gauges 部分获取值,但我的尝试似乎失败了:
XDocument xml = XDocument.Load(file);
XNamespace xmlns =XNamespace.Get("http://somestuff.new/ns");
XNamespace ns3 = XNamespace.Get("http://somestuff.new/ns3");
var Cars = from car in xml.Descendants(ns + "Cars")
select new Cars
{
CarParts = (from part in car.Descendants(ns + "Parts")
select new Parts
{
CarExtras = (from extra in part.Descendants(ns + "Extras")
select new Gauges
{
Speed = (double?)extra.Element(ns3 + "Speed") ?? 0.0,
Rpm = (int?)extra.Element(ns3 + "Rpm") ?? 0
})
})
});
我尝试了很多与命名空间的组合,因为当我到达 Gauges 时它会发生变化,但我没有得到任何返回值。
希望有人可以帮助我吗?
【问题讨论】:
-
您的示例 XML 无效。
xmlns="http://somestuff.new/ns32上至少缺少一个右引号。您的示例 XML 实际上仅使用 2 个名称空间,即数据库上的默认名称空间 (xmlns="somestuff.new/ns") 和 Gauges 上的默认名称空间 (xmlns="somestuff.new/ns32")。您没有在代码中声明后者。 -
好吧,看来 2 应该是引号(德语键盘)。我编辑了帖子并删除了所有未使用的命名空间。
标签: c# xml linq namespaces