【问题标题】:How do I save an XML node's content to a string?如何将 XML 节点的内容保存到字符串?
【发布时间】:2012-12-04 10:06:35
【问题描述】:

我有这样的 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>

...我想提取 &lt;image size="large"&gt;...&lt;/image&gt; 并将其保存为字符串。

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

我试过了

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

...但我迷路了。

做我需要做的最好的方法是什么?

【问题讨论】:

  • 我编辑它对不起,第一次发帖。我尝试使用 XmlNodeList xnList = xml.SelectNodes("image[@size='large']");
  • 没有问题。如果您需要社区的帮助,您必须证明至少您尝试过做某事,这里的人会帮助您,但他们不会为您完成工作。
  • 试试xml.SelectNodes("//image[@size='large']");
  • 好的,现在我得到了正确的数据,谢谢
  • @GonzaloHernandez 我已经编辑了您的问题文本。请检查我如何更改您的原始问题。提问时多说“爱”,避免“聊天语言”。

标签: c# xml parsing


【解决方案1】:

最好使用 LINQ 2 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>

试试这样的:

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

【讨论】:

  • 但是xpath不是更简单吗? var url = doc.XPathSelectElement("//image[@size='large']").Value
  • @L.B 我会投票支持 XDocument 而不是 XPath,因为 .NET XPath 实现不在 2.0 规范之上,而且 Linq2Xml 到目前为止功能更丰富。
  • XPathSelectElementXDocumentXElement 的扩展方法。仍然是 Linq2Xml。
  • @L.B.也许它更简单,我从未使用过它;)享受吧!
  • @L.B 是的,但我怀疑这是常规 XPath 实现的捷径。如果我错了,请纠正我(我很高兴知道)。
猜你喜欢
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多