【发布时间】:2017-10-16 19:38:01
【问题描述】:
我的 xml 结构如下,我尝试使用 linq to 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
}
【问题讨论】:
-
我不明白“我必须将所有 child2 节点值以逗号分隔”的意思。 “childs1”和“child2”是谁?
-
抱歉错过了添加包含 childs1 的 xml 文件 1
标签: c# linq linq-to-xml