[英]Search XML file using Linq for ID and return name
In the following dummy XML file, I have to find search string in the stepContent node and return the ElementID and stepID. 在下面的虚拟XML文件中,我必须在stepContent节点中找到搜索字符串,并返回ElementID和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.
我在C#中使用Linq,而我能够找到搜索字符串并返回整个节点,我无法弄清楚如何返回搜索节点的stepID和ElementID。 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,并且这些ID节点的深度可能有所不同,因此我需要一些查询来查询返回值中的名称。
<?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
"“我必须在
stepContent
节点中找到搜索字符串并返回ElementID
和stepID
”
As long as relative depth of ElementID
and stepID
from stepContent
is consistent, you can do this way : 只要
ElementID
和stepID
与stepContent
相对深度一致,就可以这样做:
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.