Razzor
Razzor

Reputation: 63

Xml Linq Find Element After another Element

I am searching for this for a long time here, but I can't get it working from other codes. I need to find the closest element to "user" (which is "robot") and write its value (it's depending on user's input). I am programming a chat-bot. This is my XML file:

<Answers>
<user>This is a message</user><robot>Here is an answer</robot>
<user>This is another message</user><robot>Here is another answer</robot>
</Answers>

In C# code i am trying something like this:

private static void Main(string[] args)
{
    XDocument doc = XDocument.Load("C:\\bot.xml");
    var userPms = doc.Descendants("user");
    var robotPm = doc.Descendants("robot");

    string userInput = Console.ReadLine();

    foreach (var pm in userPms.Where(pm => pm.Value == userInput))
    {
        Console.WriteLine  // robotPm.FindNextTo(pm)
    }
}

Simply put, I want to compare "user" input in console and in xml and if they are equal write robot's answer from xml which is responsible to specified user input. Thank you for help

Upvotes: 0

Views: 96

Answers (1)

L.B
L.B

Reputation: 116118

Simply use NextNode

Console.WriteLine(((XElement)pm.NextNode).Value);

But don't forget: Altough I've never seen a counter-example, xml parsers do not guarantee the order of elements. a better approach would be

<item>
    <q>qusetion1</q>
    <a>answer1</a>
</item>
<item>
    <q>qusetion2</q>
    <a>answer2</a>
</item>

Upvotes: 1

Related Questions