XDocument.Root.Element returns null

孤者浪人 提交于 2019-12-10 14:53:05

问题


I have XML which is like:

<?xml version="1.0" encoding="utf-16"?>
<RootNodeName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:xsd="http://www.w3.org/2001/XMLSchema" MyAttribute="7" xmlns="mylink">
  <IsValid>false</IsValid>
  <Name>some matrix</Name>
  ...Some more nodes...
</RootNodeName>

and code wich is like:

var doc = XDocument.Parse(myXmlString);
Console.WriteLine(doc.Root.Element("Name"));

and console shows just an empty space since doc.Root.Element("Name") returns null =(

While I can find this Element among doc.Root.Elements() results. doc.Root.Attribute("MyAttribute") gives correct result as well.

What is wrong with it/me?


回答1:


The <Name> element is in the mylink namespace:

XNamespace mylink = "mylink";

Console.WriteLine(doc.Root.Element(mylink + "Name"));


来源:https://stackoverflow.com/questions/13402628/xdocument-root-element-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!