In the following dummy XML file, I have to find search string in the stepContent node and return the ElementID and stepID. I am using Linq in C#, while I am able to find the search string and return the entire node, I am unable to figure out how to return the stepID and ElementID of searched node. Please note this is dummy XML and depths of these ID nodes may vary, so I need something to query them on names in the returned values.
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Elements>
<Element>
<ElementID>A001</ElementID>
<Detail><![CDATA[<ul>
<li>
For top candidates
</li>
<li>
Discount upto 50%
</li>
</ul>]]></Detail>
<Steps>
<Step>
<stepID>S001</stepID>
<StepHeading>Prepare for top candidates</StepHeading>
<stepContent><![CDATA[<ul>
<li>Some dummy text</li>
<li>Plan some dummy items.</li>
</ul>]]></stepContent>
</Step>
<Step>
<stepID>S002</stepID>
<StepHeading>Invite top candidates</StepHeading>
<stepContent><![CDATA[<ul>
<li>Dummy text for invitation.</li>
<li>Dummy text for 2nd invitation.</li>
</ul>]]></stepContent>
</Step>
</Steps>
</Element>
<Element>
<ElementID>A002</ElementID>
<Detail><![CDATA[<ul>
<li>
For next set of top candidates
</li>
<li>
Discount upto 30%
</li>
</ul>]]></Detail>
<Steps>
<Step>
<stepID>S003</stepID>
<StepHeading>Prepare for next set of top candidates</StepHeading>
<stepContent><![CDATA[<ul>
<li>Some dummy text</li>
<li>Plan some dummy items.</li>
</ul>]]></stepContent>
</Step>
<Step>
<stepID>S004</stepID>
<StepHeading>Invite next set of top candidates</StepHeading>
<stepContent><![CDATA[<ul>
<li>Dummy text for invitation.</li>
<li>Dummy text for 2nd invitation.</li>
</ul>]]></stepContent>
</Step>
</Steps>
</Element>
</Elements>
</Root>
"I have to find search string in the
stepContent
node and return theElementID
andstepID
"
As long as relative depth of ElementID
and stepID
from stepContent
is consistent, you can do this way :
resultNodes.Select(o => new YourModelClass()
{
stepId = (string)o.Parent.Element("stepID"),
elementId = (string)o.Parent.Parent.Parent.Element("ElementID")
//alternatively :
//elementId = (string)o.Ancestors("Element").First().Element("ElementID")
});
You could do this way.
var doc = XDocument.Load(filepath);
var steps = doc.Root.Descendants("Step")
.Where(e=> ((string)e.Element("stepContent").Value).ToLower().Contains("dummy text for "))
.Select(s=> new
{
StepId = s.Element("stepID").Value,
StepHeading = s.Element("stepID").Value
});
Check this Demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.