从子节点获取值

时间:2017-10-16 19:38:02

标签: c# linq linq-to-xml

我有如下的xml结构,我尝试使用linq获取节点到xml。我有点困惑如何阅读孩子的子节点,我将不得不将所有child2节点值作为逗号分隔值。并且还必须读取子节点下存在的任何动态节点。 以下是xml示例。

文件1:

<parent>
 <doc>
  <order>testorder</order>
   <preorder>yes</preorder>
    <child>
     <childs1>
      <child2>abc</child2>
      <child2>efg</child2>
     </childs1>
     <preview>current</preview>
     <provision>enable</provision>
    </child>
   </doc>
  </parent>

文件2:

<parent>
 <doc>
  <order>testorder</order>
   <preorder>yes</preorder>
    <child>
     <preview>current</preview>
     <provision>enable</provision>
     <other>abc</other>
    </child>
  </doc>
 </parent>

我的sudo代码:

XDocument xdoc = XDocument.Load(file);
var customers =
from cust in xdoc.Descendants("doc")
      select new 
        {
        Title = cust.Element("order").Value,
        preorder = cust.Element("preorder").Value,
        innernode= from inner in cust.Elements("child")
                                  select new {
                                      site = (inner.Element("preview") != null) ? inner.Element("preview").Value : null,
                                      node=(inner.Element("childs1") != null) ?  string.Join(",",  from seg in inner.Elements("child2") select seg.Value) :null,
                              Should store if any extra dynamic nodes are there ,
                                     },
                         };
                          foreach(var item in customers)
                        {
                                               // read all nodes
                        }

1 个答案:

答案 0 :(得分:1)

您提取child2的代码正试图查看doc的后代,但您想查看childs1的后代。至于动态字段,您可以通过创建字典来获取与硬编码字符不匹配的任何元素,如下所示。

var customers =
    from cust in xdoc.Descendants("doc")
    select new
    {
        Title = cust.Element("order").Value,
        preorder = cust.Element("preorder").Value,
        innernode = from inner in cust.Elements("child")
                    select new
                    {
                        site = (inner.Element("preview") != null) ? inner.Element("preview").Value : null,
                        node = (inner.Element("childs1") != null) ? string.Join(",", from seg in inner.Elements("childs1").Elements("child2") select seg.Value) : null,
                        dynamicElements = inner.Elements()?.Where(e => e.Name != "preview" && e.Name != "childs1")?.ToDictionary(e => e.Name, e => e.Value)
                    },
    };