tags:

views:

38

answers:

1

Hai I have An XDocument .All nodes in this document have an attribute UserId. I want to change the value of this attribute 0 to 1. How to do this using Linq query. I used this.

MyNewUserPermission.Descendants("menuNode").Single.SetAttributeValue("userId", Me.UserId)

It's not Working.Error shows

Sequence contains more than one element

XmlFile

<menuNode url="" title="Register" id="mnuMainRegister" value="true" userId ="0">
      <menuNode url="Company.aspx?Name=Company" title="Company" id="mnuCompany" value="true" userId ="0"/>
      <menuNode url="Company.aspx?Name=User" title="SubCategory" id="mnuSubcategory" value="true" userId ="0"/>
      <menuNode url="Common.aspx?Name=Category" title="Category" id="mnuCategory" value="true" userId ="0"/>
      <menuNode url="Common.aspx?Name=Employee" title="Employee" id="mnuEmployee" value="true" userId ="0"/>
      <menuNode url="Common.aspx?Name=Product" title="Product" id="mnuProduct" value="true" userId ="0"/>
      <menuNode url="Common.aspx?Name=SaleArea" title="SaleArea" id="mnuSaleArea" value="true" userId ="0"/>
      <menuNode url="Common.aspx?Name=SalePlace" title="SalePlace" id="mnuPlace" value="true" userId ="0"/>
    </menuNode>

I dont know this can be be done using linq . Other wise just tell whats wrong with my code.

+1  A: 

Since your menuNode contain nested menuNodes the Single operation will throw an exception as MyNewUserPermission.Descendants("menuNode") will return multiple values and not just one as required by the Single operation.

Try the .First operation instead of the .Single operation or MyNewUserPermission.Root.SetAttributeValue("userId", Me.UserId) if menuNode is the root of the document.

If you want to set all the menuNode elements' attributes (including the nested ones) then loop through all the MyNewUserPermission.Descendants("menuNode") elements and set each one's attribute.

Cornelius
thank you , I am asking without using a loop , can I do the same thing?
Vibin Jith
If you want to update each node then you will require a loop. Linq is good for querying but in general updating of more than one item in a collection still requires a loop.
Cornelius
Exactly . I want to just confirm it. thank you
Vibin Jith