【问题标题】:What's wrong on taking this XML element?使用这个 XML 元素有什么问题?
【发布时间】:2013-11-11 10:21:32
【问题描述】:

XML:

<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
    ...
   <author>
      <name>Seamless</name>
      <uri>https://gdata.youtube.com/feeds/api/users/SeamlessR</uri>
   </author>

代码:

var ns = XNamespace.Get("http://www.w3.org/2005/Atom");
var name = xDoc.Descendants(ns + "entry").First().Element("author").Element("name").Value;

上面写着Object reference not set to an instance of an object.

【问题讨论】:

  • 你有没有通过调试器看看NULL到底是什么?
  • @O.R.Mapper:不,它将使用XName +(XNamespace, string) 运算符。

标签: c# .net xml parsing xml-parsing


【解决方案1】:

您正在使用Element("author")Element("name"),就好像它们不在命名空间中一样。命名空间将默认为与entry 相同的命名空间,因此您需要:

var ns = "http://www.w3.org/2005/Atom"; // Just use an implicit conversion
var name = xDoc.Descendants(ns + "entry")
               .First()
               .Element(ns + "author")
               .Element(ns + "name")
               .Value;

【讨论】:

  • 哦,以前不知道这个!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多