Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Update a node attribute in xml using Linq query?

Tags:

linq

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.

like image 229
Vibin Jith Avatar asked May 20 '26 08:05

Vibin Jith


1 Answers

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.

like image 60
Cornelius Avatar answered May 22 '26 01:05

Cornelius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!