-2

So, I have the xml file with structure:

<?xml version="1.0" encoding="utf-8"?>
<Students>
  <Student Id="0">
    <FirstName>Robert</FirstName>
    <Last>Jarman</Last>
    <Age>21</Age>
    <Gender>0</Gender>
  </Student>
  <Student Id="1">
    <FirstName>Leona</FirstName>
    <Last>Menders</Last>
    <Age>20</Age>
    <Gender>1</Gender>
  </Student>
<Students>

What is the best way to read(one or several elements), write, delete and update records inside a document?

Roman
  • 35
  • 6
  • 1
    In current format your question is too broad. Specify `one` problem per question. So what do you want to know exactly. If you can't decide you can always write in google how to parse xml document in C# ! – mybirthname Dec 03 '16 at 15:45
  • I want to work with nodes and have possibility to create a new file with the same structure if it won't exist. – Roman Dec 03 '16 at 15:58

1 Answers1

1

Best way is usin XDocument

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = @"
            <root>
                <child id='1'/>
                <child id='2'>
                    <grandchild id='3' />
                    <grandchild id='4' />
                </child>
            </root>";
        XDocument doc = XDocument.Parse(xml);

        foreach (XElement element in doc.Descendants("grandchild"))
        {
            Console.WriteLine(element);
        }

        XDocument doc = XDocument.Parse(xml); 
        IEnumerable<XElement> childList =  
            from el in doc.Elements()  
            select el;  
        foreach (XElement e in childList)  
            Console.WriteLine(e); 
        }
    }
}

Result is :

<grandchild id="3" />
<grandchild id="4" />

<root>
    <child id='1'/>
    <child id='2'>
        <grandchild id='3' />
        <grandchild id='4' />
    </child>
</root>

If you read xml from file you can use

XDocument doc = XDocument.Load("Test.xml");
lucaT
  • 123
  • 1
  • 5