使用where条件使用Linq C#读取XML

我尝试为我的业务提供一些服务,但是它不起作用。

<item>
<key>12323</key>
<summary></summary>
<reporter username="12313asdf">1232 asdf iii</reporter>
   <cusomfields>
        <customfield id="customfield_37723" key="xyz">
          <customfieldname>First Name</customfieldname>
          <customfieldvalues>
            <customfieldvalue>Klaus</customfieldvalue>
          </customfieldvalues>
        </customfield>
   </customfields>
</item>

我用这段代码创建了一个c#方法->但它不起作用:(

            XDocument doc = XDocument.Load(fileName);

            var obj = (from c in doc.Descendants("item")
                       select new ServiceRequest_NewUser()
                       {
                           TicketID = c.Element("key").Value,
                           Summary = c.Element("summary").Value,
                           ReporterNT = c.Element("reporter").Attribute("username").Value,
                           ReporterFull = c.Element("reporter").Value,
                           FirstName = (from f in c.Element("customfieldvalue").Value
                                        where c.Element("id").Attribute("customfield_37723") == true
                                        select f)

                           //c.Element("customfieldvalue").Value.Where(c.Attribute("id").Value.Equals("customfield_37723"))
                       }).ToList();

我的错在哪里我在comment标签中做了另一种代码版本。我需要输出值“ Klaus”。

预先感谢您的帮助。

评论
Lucy
Lucy

如果您希望在名字中看到克劳斯,则应该这样写:

            var obj = (from c in doc.Elements("item")
                select new ServiceRequest_NewUser
                {
                    TicketID = c.Element("key")?.Value,
                    Summary = c.Element("summary")?.Value,
                    ReporterNT = c.Element("reporter")?.Attribute("username")?.Value,
                    ReporterFull = c.Element("reporter").Value,
                    FirstName = (from f in c.Descendants("customfieldvalue")
                        where c.Element("customfield")?.Attribute("id")?.Value == "customfield_37723"
                        select f).FirstOrDefault()?.Value
                }).ToList();
点赞
评论