user9250176
user9250176

Reputation:

Extract data from xml string

Let's say I have an xml string:

<?xml version="1.0" encoding="UTF-8"?>
<Return version="1.0">
<File>1</File>
<URL>2</URL>
<SourceUUID>1191CF90-5A32-4D29-9F90-24B2EXXXXXX0</SourceUUID>
</Return>

and I want to extract the value of SourceUUID, how?

I tried:

           XDocument doc = XDocument.Parse(xmlString);

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

Upvotes: 0

Views: 1407

Answers (1)

Matt Hogan-Jones
Matt Hogan-Jones

Reputation: 3103

If all you want is the content of the SourceUUID element, and there's only going to be 1 in the XML, you can do this:

        XDocument doc = XDocument.Parse(xmlString);
        var value = doc.Descendants("SourceUUID").SingleOrDefault()?.Value;

If there are going to be more than one, you can do this:

        var values = doc.Descendants("SourceUUID").Select(x => x.Value);

This gives you an enumerable of strings that are the text values of the elements.

Upvotes: 2

Related Questions