按前一个节点的值检索下一个xml节点 - 使用linq

时间:2016-08-18 10:38:50

标签: c# linq linq-to-xml

我有以下xml:

<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的给定问题得到答案。我该怎么做?

当前代码:

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

我使用<answer>标记获得输出。如何删除它?

2 个答案:

答案 0 :(得分:0)

这样做的一种方法是使用Linq to 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实例,这是一个更难以使用的类,所以您可以在上面执行此操作。

答案 1 :(得分:0)

这只有在有序的q和a

对时才有效
    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>