如何将XML节点的内容保存到字符串? [英] How do I save an XML node's content to a string?

查看:187
本文介绍了如何将XML节点的内容保存到字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的XML:

<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>

...而且我想提取<image size="large">...</image>并将其另存为字符串.

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

我的目标是获取所提取元素的子文本节点.例如http://userserve-ak.last.fm/serve/174s/42566323.png.

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

我尝试过

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?

推荐答案

最好使用LINQ 2 XML:

It's better to use LINQ 2 XML:

假设您具有以下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>

尝试这样的事情:

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

这篇关于如何将XML节点的内容保存到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆