3

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

2
  • Can you add a short but complete program that demonstrates the problem? Commented Aug 17, 2011 at 14:55
  • i` mafraid i can`t, the thing is it gives me null object reference error but if i add another element above <parameters it works Commented Aug 17, 2011 at 14:57

3 Answers 3

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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; }

Comments

0

Just use the Root

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.