Reputation: 127
I have xml structure as below and i try to fetch nodes using linq to xml. I am kind of stuck how to read child's child node also I will have to get all child2 node values as coma separated values. And also have to read any dynamic nodes present under child node. Here are sample xml's.
File 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>
File 2 :
<parent>
<doc>
<order>testorder</order>
<preorder>yes</preorder>
<child>
<preview>current</preview>
<provision>enable</provision>
<other>abc</other>
</child>
</doc>
</parent>
My sudo code :
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
}
Upvotes: 2
Views: 354
Reputation: 464
Your code to fetch child2
is trying to look in doc
's descendants, but you want to look at childs1
's descendants. As for dynamic fields you can do it by creating a dictionary to get any elements that don't match the hardcoded ones, as i did below.
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)
},
};
Upvotes: 1