3

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.

2
  • can you show us the XML document? Or at least the part of it you're trying to update? Commented Mar 5, 2010 at 6:44
  • Now tell, i updated my question. Commented Mar 5, 2010 at 6:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you , I am asking without using a loop , can I do the same thing?
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.

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.