【问题标题】:LINQ parse xml file and get values from specific nodesLINQ 解析 xml 文件并从特定节点获取值
【发布时间】:2018-12-13 18:07:55
【问题描述】:

我有一个 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();

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

提前致谢。

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

    这是您的工作示例。你可以从这里去

    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 
                 let pos = (el.Element("position") == null ? string.Empty : el.Element("position").Value)
                 where el.Element("name").Value.Equals("Val1") 
                 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 - 牧师

    【讨论】:

      【解决方案2】:

      这会给你IEnumerable&lt;AnonymousType&gt;

                   var valLst =(from el in details 
                   select new
                   {
                       Name = el.Element("name").Value,
                       Position = el.Element("position")?.Value ?? ""
                   });
      

      输出:

            "{ Name = Val1, Position =  }"
            "{ Name = Val1, Position = Priest }"`
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-30
        • 2014-05-04
        • 2012-12-13
        • 1970-01-01
        相关资源
        最近更新 更多