2016-08-18 36 views
-3

我有以下XML:检索下一个XML节点 - 使用LINQ

<century> 
<question>What is silvia</question> 
<answer>silvia is artificial intelligence</answer> 
<question>What is your name</question> 
    <answer>my name is RAMESH</answer> 
</century> 

我想获得基于使用LINQ给定的问题的答案。我应该怎么做?

当前代码:与<answer>标签

string textToSearch = "When did AI research start"; 
XDocument doc = XDocument.Load(@"D:\SILVIA\New task\FinalXml.xml"); 

var q = doc.Descendants("CenturySoft") 
      .Descendants("question") 
      .Where(item => item.Value == textToSearch) 
      .Select(item => item.NextNode) 
      .FirstOrDefault(); 

我得到的输出。如何删除它?这样做的

回答

0

一种方式,以便与LINQ到XML:

var result = XDocument.Load("data.xml") 
     .Descendants("century") 
     .SelectMany(element => element.Descendants("question") 
             .Zip(element.Descendants("answer"), 
              (q,a) => new { 
               Question = q.Value, 
               Answer = a.Value 
              })) 
     .ToList(); 

注意,这将无法正常工作,如果你有一个以上的答案为一个问题,或者如果你有在的排序问题问题,回答

做的另一种方法(使用XPathSelectElement扩展方法 - 添加using System.Xml.XPath)是:

var question = "What is silvia"; 

var answer = XDocument.Load("data.xml") 
         .XPathSelectElement($"century/question[\"{question}\"]") 
         .NextNode; 

按照你的更新,你可以这样做:

var q = doc.Descendants("century") 
      .Descendants("question") 
      .Where(item => item.Value == textToSearch) 
      .Select(item => item.ElementsAfterSelf().FirstOrDefault()) 
      .FirstOrDefault().Value; 

当使用NextNode你得到一个XNode实例,它是一个比较难用类因此,你可以像在上面。

+0

@Bhimana Ramesh - 它有助于你解决问题吗? –

+0

没有没有解决。我有LINQ查询这样的字符串textToSearch =“AI研究何时开始”; XDocument doc = XDocument.Load(@“D:\ SILVIA ​​\ New task \ FinalXml.xml”); (item => item.Value == textToSearch) .Select(item => item.NextNode) .FirstOrDefault(); var q = doc.Descendants(“CenturySoft”).Dececendants(“question”) 。在这我得到输出为我认为是的,但我们还没有在这个过程可以开始的AI水平。。我想输出为没有答案标签。请提供任何解决方案。谢谢。 –

+0

@BhimanaRamesh - 检查更新 –

0

这只会只要有命令的对Q的工作,并且一个是

Dim xe As XElement 
    'to load from a file 
    ' xe = XElement.Load("Your Path Here") 

    ' for testing 
    xe = <century> 
      <question>What is silvia</question> 
      <answer>silvia is artificial intelligence</answer> 
      <question>What is your name</question> 
      <answer>my name is RAMESH</answer> 
     </century> 

    Dim qs As IEnumerable(Of XElement) = xe...<question> 
    Dim ans As IEnumerable(Of XElement) = xe...<answer> 


    For x As Integer = 0 To qs.Count - 1 
     Debug.WriteLine("Q: {0}? A: {1}", qs(x).Value, ans(x).Value) 
    Next 

如果XML有不同的结构(更好的?)这会更容易些。

Dim xe As XElement 
    xe = <QandA> 
      <item> 
       <question>What is silvia</question> 
       <answer>silvia is artificial intelligence</answer> 
      </item> 
      <item> 
       <question>What is your name</question> 
       <answer>my name is RAMESH</answer> 
      </item> 
     </QandA>