开发者

LINQ to XML C# get root element attribute

开发者 https://www.devze.com 2023-03-28 13:55 出处:网络
Lts say i have XElement object doc开发者_如何学编程: <parameters mode=\"solve\"> <inputs>

Lts say i have XElement object doc开发者_如何学编程:

<parameters mode="solve">
  <inputs>
    <a>value_a</a>
      ...
       ...

how do i get the value of the attribute of the first element (parameters), in other words how do i check which mode is it on.

if i write

if ((string)doc.Element("parameters").Attribute("mode").Value == "solve") { mode = 1; }

it gives me null object reference error


If doc is an XElement, as you say in your question, then you probably don't need to match it again:

if (doc.Attribute("mode").Value.ToString() == "solve") {
    mode = 1;
}

If it is an XDocument, then you can use its Root property to refer to the document element:

if (doc.Root.Attribute("mode").Value.ToString() == "solve") {
    mode = 1;
}


When you are calling doc.Element("parameters"), you are trying to look at the elements below the root element (in this case, the elements at the same level as <inputs>). You want to do this instead:

if (input.Attribute("mode").Value == "solve") { mode = 1; }


Just use the Root

if (doc.Root.Attribute("mode").Value.Equals("solve"))
{
   mode = 1;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号