LINQ 解析 xml 文件并从特定节点获取值

我有一个 xml 文件,我尝试从特定节点检索数据。但是有些节点丢失了,所以我想返回空字符串。下面是我的代码示例,我正在使用 LINQ。


string xml = @"<root>

                <employee>

                 <name>Val1</name>

                 <age>30</age>

                </employee>

                <employee>

                 <name>Val1</name>

                 <age>30</age>

                 <position>Priest</position>

                </employee>

               </root>";             


   XElement x = XElement.Parse(xml);

   IEnumerable<XElement> details = x.Elements();

   var valLst = (from el in details 

                 where el.Element("name").Value.Equals("Val1") 

                 select el.Value).ToList();

详细信息对象包含 2 个员工节点及其子节点,因此我想根据名称节点值获取子节点值。此外,我想为丢失的节点返回空字符串(例如,位置节点从第一部分但存在于第二部分)


提前致谢。


天涯尽头无女友
浏览 196回答 2
2回答

噜噜哒

这是您的工作示例。你可以从这里string xml = @"<root>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <employee>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<name>Val1</name>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<age>30</age>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </employee>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <employee>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<name>Val1</name>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<age>30</age>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<position>Priest</position>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </employee>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</root>";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;XElement x = XElement.Parse(xml);IEnumerable<XElement> details = x.Elements();var valLst = (from el in details&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;let pos = (el.Element("position") == null ? string.Empty : el.Element("position").Value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;where el.Element("name").Value.Equals("Val1")&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select new {n = el.Value, p = pos}).ToList();Console.WriteLine(valLst[0].n + " - " + valLst[0].p);Console.WriteLine(valLst[1].n + " - " + valLst[1].p);输出:Val130 -Val130Priest - 牧师

翻过高山走不出你

这会给你一个IEnumerable<AnonymousType>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var valLst =(from el in details&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select new&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Name = el.Element("name").Value,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Position = el.Element("position")?.Value ?? ""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});输出:&nbsp; &nbsp; &nbsp; "{ Name = Val1, Position =&nbsp; }"&nbsp; &nbsp; &nbsp; "{ Name = Val1, Position = Priest }"`
打开App,查看更多内容
随时随地看视频慕课网APP