Gonzalo Hernandez
Gonzalo Hernandez

Reputation: 737

How do I save an XML node's content to a string?

I have and XML like this:

<album>
  <image size="small">http://exaplem/example.jpg</image>
  <image size="medium">http://exaplem/example.jpg</image>
  <image size="large"> http://userserve-ak.last.fm/serve/174s/42566323.png </image>
  <image size="extralarge"> http://exaplem/example.jpg </image>
</album>

...and I want to extract and save <image size="large">...</image> as string.

My goal is obtaining the child text node of the extracted element. For example http://userserve-ak.last.fm/serve/174s/42566323.png.

I've tried with

XmlNodeList xnList = xml.SelectNodes("image[@size='large']");
foreach (XmlNode xn in xnList)
{
    .....
}

... but I'm lost.

What's the best way to do what I require to do?

Upvotes: 1

Views: 229

Answers (1)

Vitaliy
Vitaliy

Reputation: 718

It's better to use LINQ 2 XML:

Assuming you have following xml document:

</album>
  <image size="small">http://exaplem/example.jpg</image>
  <image size="medium">http://exaplem/example.jpg</image>
  <image size="large"> http://userserve-ak.last.fm/serve/174s/42566323.png </image>
  <image size="extralarge"> http://exaplem/example.jpg </image>
</album>

Try something like this:

var doc = XDocument.Parse(yourDocumentString);
var largeImageUrl = doc.Root.Elements("image").Single(image => image.Attribute("size").Value == "large").Value;

Upvotes: 2

Related Questions