views:

18

answers:

1

I have this xml structure:

<Departments>
   <Department Id="a Guid" IsVisible="True" />
</Departments>

I have created the xml file with:

<Departments />

Now I want to add a bool value to IsVisible for a certain Id

If that Id does not exist in the xml file I want to make an insert creating

a new Department with Id + IsVisible.

My first problem starts here:

XElement dep= xDoc.Descendants("Departments").Descendants("Department")
                  .Where(d => d.FirstAttribute.Value == Id).FirstOrDefault();
if (dep != null)
{
    // The node <Department ... /> exist 
}

Error message: The Id does not exist in the current context

Of course it does not but that is the reason why I want to check for....

Also how can I check for the Id and compare it with my Id from another List?

Above I ask .Value == Id but I want also compare the value and if its true return the node.

Really I have an XLinq book before me but nothing helped. What a bad buy with non-practical samples (Linq for Visual C# 2008)

+1  A: 

I doubt that "The Id does not exist in the current context" is actually the error message.

I think it's more likely to be:

The name 'Id' does not exist in the current context

... which is very different. That's saying it doesn't know which variable you're talking about. It's important to quote exact error messages.

Now, your question isn't very clear - at one point you're talking about searching for "a certain id" and later you talk about finding out comparing an id with "my id from another list". Do you have a variable with the id you're looking for? Is this just a typo, and it should be "id" instead of "Id"?

Jon Skeet
Yes I have a variable with an Id in it. And I want to compare this variable with the ID=... in the xml file.And yes about the error message you was right. Its "Name Id..."
Lisa
@Lisa: What is that variable *called* though. It looks like it's not "Id". Just replace "Id" in your query with the *actual* name of the variable, and it could work... although only if it really *is* the first attribute of the element that you're looking for. (Why not look by the *name* of the attribute?)
Jon Skeet
"(Why not look by the name of the attribute?)"this was my initial Intention but did not know how, so I choosed First() :P
Lisa