Saturday, 16 August 2014

LinqToXML: accessing child elements



I trying to figure out a solution for a tiny problem I have, but I didn't have much success in last two days. I've went through many posts here but I failed to find an adequate solution for myself. I know it's probably basic question for you guys, but it seems like I've lost focus and can think clearly about this issue.


So, this is the issue. I have a sample XML below, with the structure I need. What I want is to read this XML, go to the event I want and than read/ store all test elements.



<Config>
<Events>
<Event_1>
<NameOfEvent>SomeName:</NameOfEvent>
<test id="test001">
<xpath>"some xpath"</xpath>
<value>someValue1</value>
<tagName>none</tagName>
</test>
<test id="test002">
<xpath>"some xpath"</xpath>
<value>someValue2</value>
<tagName>none1</tagName>
</test>
<test id="test003">
<xpath>"some xpath"</xpath>
<value>someValue3</value>
<tagName>none2</tagName>
</test>
</Event_1>
</Events>
</Config>


What I`ve done so far is this:



string EventCode="Event_1";
var doc= XDocument.Load(@"C:\new\test\testConfig.xml");
var result = from y in doc.Descendants(EventCode).
Where(y =>(string)y.Element("path").Attribute("id")=="test001"
{
NameOfEvent = y.Element("NameOfEvent").Value,
xpath= y.Element("test").Element("xpath").Value
value =y.Element("test").Element("value").Value,
tag =y.Element("test").Element("tagName").Value
};


Than, I want to use foreach loop, to access all test elements. But, I`m only able to access chiled nodes of first element test. Can you help with this? Thanks a lot in advance!!!


No comments:

Post a Comment