0

i want to extract a value from an XML File and i already saw some solutions but i couldnt find one that works for me.

Here is my Sample XML File (i want to extract the Serial Number)

<Other TrashCodeSample="SampleTextHere">
    <Data key="SerialNumber">911987082611993854940173</Data><Data key="TrashNumber2">5346587345345</Data></Other>

I already got some Code but it only gives me the last Value in "Data"

            XDocument doc = XDocument.Load(label3.Text);

            var authors = doc.Descendants("Data");

            foreach (var author in authors)
            {
                textBox1.Text = (string) author;
            }

the Serial Number is the Value i want to get:

<Data key="SerialNumber">911987082611993854940173</Data>
  • if Possible i want to Edit the Serial Number inside the XML

it would be easy if i only had one "Data" but thats not the case.. :/

RaINi
  • 53
  • 1
  • 5
  • Possible duplicate of [Reading Xml with XmlReader in C#](http://stackoverflow.com/questions/2441673/reading-xml-with-xmlreader-in-c-sharp) – mmmmmm Oct 24 '16 at 17:19

1 Answers1

0

If you use LINQ and C# then try doc.Descendants("Data").First(d => (string)d.Attribute("key") == "SerialNumber") to access that data element. You can then read out or set its .Value property.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • do you have an idea how i can modify the Serial Number? – RaINi Oct 24 '16 at 17:47
  • I wrote you can set the `.Value` property so `doc.Descendants("Data").First(d => (string)d.Attribute("key") == "SerialNumber") = "1234567890";` modifies the contents of that `data` element. You will then have to call the `doc.Save("newfile.xml")` method to save back to a file. – Martin Honnen Oct 24 '16 at 17:51