How to update node attribute in xml using Linq query?

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

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

This does not work. Shows her

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 do not know that this can be done using linq. Other reasonable ones will just say what is wrong with my code.

+3
source share
1 answer

Since your menuNode contains nested menuNodes, a single operation throws an exception, as it MyNewUserPermission.Descendants("menuNode")will return multiple values, and not just one as required by a single operation.

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

menuNode ( ), MyNewUserPermission.Descendants("menuNode") .

+1

Source: https://habr.com/ru/post/1735545/


All Articles