2016-03-25 75 views
1

在以下虛擬XML文件中,我必須在stepContent節點中查找搜索字符串並返回ElementID和stepID。我在C#中使用Linq,而我能夠找到搜索字符串並返回整個節點,我無法弄清楚如何返回搜索節點的stepID和ElementID。請注意,這是虛擬的XML,這些ID節點的深度可能會有所不同,所以我需要在返回的值中查詢它們的名稱。使用Linq搜索XML文件並返回名稱

<?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> 
+0

串xmlpath中使用Server.Mappath =( 「myXMLPath.xml」); var xml = XDocument.Load(@xmlPath); XDocument xDocument = XDocument.Parse(xml.ToString()); var resultNodes = xDocument.Descendants(「stepContent」)。Where(i => i.Value.ToLower()。Contains(searchString)); 如何從結果集中獲取ID? – onlynitins

+2

[編輯]這個問題,並把你的C#代碼放在那裏(與你的XML分開的代碼塊) – har07

回答

0

「我一定要找到在stepContent節點搜索字符串,並返回ElementIDstepID

只要ElementID相對深度和stepIDstepContent是一致的,你可以這樣做:

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") 
      }); 
0

你可以這樣做。

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 
      }); 

檢查此Demo