0

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);
            }
9
  • is this line gives error : XDocument doc = XDocument.Parse(readStream.ReadToEnd()); Commented Mar 13, 2018 at 13:24
  • @PranayRana that's the xml string i edited, see now Commented Mar 13, 2018 at 13:25
  • 1
    Your code does not produce this error. Commented Mar 13, 2018 at 13:27
  • Forget about the error, I only want to extract the data, how please? Commented Mar 13, 2018 at 13:28
  • 1
    I would suggest you edit your question to remove mentions of this elusive error, and instead make it clearer that you want to extract the value of the specified element. Commented Mar 13, 2018 at 13:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@tgg I really encourage you to read more about LINQ to XML - it's an extremely useful way of consuming XML data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.