Search code examples
c#xml-parsingreadxml

Read next value in XML file


I have a XML file like that:

    <key>businessAddress</key>
    <string>Moka</string>
    <key>businessName</key>
    <string>Moka address</string>
    <key>Id</key>
    <string>39</string>
    <key>Cat</key>
    <string>216</string>
    <key>deals</key>

I want to read the next <string> value if the key is Id

So what I did is this:

XmlTextReader reader = new XmlTextReader(file);

while (reader.Read())
{
    if (reader.Value.Equals("Id"))
    {
        reader.MoveToNextAttribute
    }  
}

but I didn't succeed.

Thanks for help


Solution

  • You could use a boolean flag to indicate whether you should read the value of the next element:

    bool shouldReadId = false;
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Text && shouldReadId)
        {
            Console.WriteLine(reader.Value); // will print 39
            shouldReadId = false;
        }
    
        if (reader.Value.Equals("Id"))
        {
            // indicate that we should read the value of the next element
            // in the next iteration
            shouldReadId = true;
        }
    }