How can i extract one value from this .xml to a string? c#

114 Views Asked by At

The xml file

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<MPL Version="2.0" Title="JRSidecar" PathSeparator="\">
<Item>
<Field Name="Filename">F:\FILMS\2 Guns.mkv</Field>
<Field Name="Rating">3</Field>
<Field Name="Genre">ACTION</Field>
</Item>
</MPL>

i start :

var document = XDocument.Load(@"F:\test\2 Guns.xml");

after i try :

DataSet ds = new DataSet();ds.ReadXml(@"F:\test\2 Guns.xml");
string note = ds.Tables["ITEM"].Rows[0][1].ToString();
var rating = document.Descendants("Rating").Select(element => element.Value);

i miss something... thanks for your help. After i will put that different values ( filename, rating, genre.. ) in a dataGridView1 (i know how).

1

There are 1 best solutions below

1
Yitzhak Khabinsky On BEST ANSWER

It is better to use LINQ to XML API. It is available in the .Net Framework since 2007.

c#

void Main()
{
    const string filePath = @"e:\Temp\Stegau.xml";
    XDocument xdoc = XDocument.Load(filePath);

    string Filename = xdoc.Descendants("Field").Where(v => v.Attribute("Name")?.Value == "Filename").FirstOrDefault()?.Value;
    string Rating = xdoc.Descendants("Field").Where(v => v.Attribute("Name")?.Value == "Rating").FirstOrDefault()?.Value;
    string Genre = xdoc.Descendants("Field").Where(v => v.Attribute("Name")?.Value == "Genre").FirstOrDefault()?.Value;

    Console.WriteLine("Filename='{0}', Rating='{1}', Genre='{2}'",
        Filename, Rating, Genre);
}

Output

Filename='F:\FILMS\2 Guns.mkv', Rating='3', Genre='ACTION'