How Update a node attribute in xml using Linq query?
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="mnuSubca开发者_开发百科tegory" 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.
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.
精彩评论