2013-01-22 31 views
0

鉴于下面的XML:的XElement空时属性存在

<root xmlns="http://tempuri.org/myxsd.xsd"> 
    <node name="mynode" value="myvalue" /> 
</root> 

并给予下述的代码:

string file = "myfile.xml"; //Contains the xml from above 

XDocument document = XDocument.Load(file); 
XElement root = document.Element("root"); 

if (root == null) 
{ 
    throw new FormatException("Couldn't find root element 'parameters'."); 
} 

如果根元素包含xmlns属性那么变量根为空。如果我删除了xmlns属性,那么root不是null。

任何人都可以解释为什么这是?

回答

0

当你声明你的根元素像<root xmlns="http://tempuri.org/myxsd.xsd">这意味着你的根元素的所有后代在http://tempuri.org/myxsd.xsd命名空间。默认情况下,元素的名称空间有一个空的名称空间,XDocument.Element会查找没有名称空间的元素。如果你想访问一个名字空间的元素,你应该明确地指定这个名字空间。

var xdoc = XDocument.Parse(
"<root>" + 
    "<child0><child01>Value0</child01></child0>" + 
    "<child1 xmlns=\"http://www.namespace1.com\"><child11>Value1</child11></child1>" + 
    "<ns2:child2 xmlns:ns2=\"http://www.namespace2.com\"><child21>Value2</child21></ns2:child2>" + 
"</root>"); 

var ns1 = XNamespace.Get("http://www.namespace1.com"); 
var ns2 = XNamespace.Get("http://www.namespace2.com"); 

Console.WriteLine(xdoc.Element("root") 
         .Element("child0") 
         .Element("child01").Value); // Value0 

Console.WriteLine(xdoc.Element("root") 
         .Element(ns1 + "child1") 
         .Element(ns1 + "child11").Value); // Value1 

Console.WriteLine(xdoc.Element("root") 
         .Element(ns2 + "child2") 
         .Element("child21").Value); // Value2 

对于你的情况

var ns = XNamespace.Get("http://tempuri.org/myxsd.xsd"); 
xdoc.Element(ns + "root").Element(ns + "node").Attribute("name")