【问题标题】:XElement null when attributes exist当属性存在时 XElement null
【发布时间】:2013-01-23 06:10:34
【问题描述】:

给定以下 xml:

<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 属性,则变量 root 为空。如果我删除 xmlns 属性,则 root 不为空。

谁能解释这是为什么?

【问题讨论】:

    标签: xelement


    【解决方案1】:

    当您声明像&lt;root xmlns="http://tempuri.org/myxsd.xsd"&gt; 这样的根元素时,这意味着您的根元素的所有后代都在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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      相关资源
      最近更新 更多