Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 学习Linq到XML并尝试从XML节点创建对象_C#_Xml_Linq - Fatal编程技术网

C# 学习Linq到XML并尝试从XML节点创建对象

C# 学习Linq到XML并尝试从XML节点创建对象,c#,xml,linq,C#,Xml,Linq,我正在学习LINQ转换为XML 假设我有这样一个xml: <main> <machine> <car name="HONDA"> <model name="ACCORD"/> </car> <car name="HONDA"> <model name="CRV"/>

我正在学习LINQ转换为XML

假设我有这样一个xml:

<main>
    <machine>
            <car name="HONDA">
                <model name="ACCORD"/>
            </car>
            <car name="HONDA">
                <model name="CRV"/>
            </car>
            <car name="FORD">
                <model name="FOCUS"/>
            </car>
            etc.......        
    </machine>
</main>
使用LINQ如何在我的语句中设置“模型”

    var cars = from g in doc.Elements("main").Descendants("machine")
                 select g;
    var listCars = from c in cars.Descendants("car")
                 select new MyCar
                 {
                     Make = c.Attribute("name").Value,
                     Model= ""
                 };
我使用的是4.0框架。

您可以使用以下方法:

更新 如果将xml模式更改为类似于您在注释中显示的内容,则可以通过以下方式过滤您的汽车:

var listCars = from c in cars.Descendants("car")
               let doors= c.Elements("model").FirstOrDefault(e=>e.Attribute("name").Value=="doors")
               where doors!=null && doors.Value=="4 Doors"// this way you can get the cars that only have 4 doors
               select new MyCar
               {
                  Make = c.Attribute("name").Value,
                 //...
               };

c.model.First().Attribute(“name”).Value
谢谢。我最初尝试时没有使用.First()。如果xml发生更改,是否可以在Model语句中添加where子句?例4门在这种情况下,我会找到“Car”元素并加载其值,然后在检查属性值“name”的基础上从Car的子元素加载任何附加值,以确定元素的值。谢谢您提供的示例。这将帮助我开始理解我可以/不能用linq到xml做什么。
var listCars = from c in cars.Descendants("car")
               select new MyCar
               {
                  Make = c.Attribute("name").Value,
                  Model= c.Element("model").Attribute("name").Value
               };
var listCars = from c in cars.Descendants("car")
               let doors= c.Elements("model").FirstOrDefault(e=>e.Attribute("name").Value=="doors")
               where doors!=null && doors.Value=="4 Doors"// this way you can get the cars that only have 4 doors
               select new MyCar
               {
                  Make = c.Attribute("name").Value,
                 //...
               };