Ole
Ole

Reputation: 41

How to change an attribute in a subnode in C#?

I want to change the attribute value (in this case "51") of the "NextMemberId" in an xml file that looks like this:

<File>
  <MemberList>
    <NextMemberId Value="51" />
    <Member Id="1" ..... />
    <Member Id="2" ..... />
  </MemberList>
</File>

The following code works, but I would like to know if it can be done in a more direct way without having to run a foreach loop:

var memberId = 1;

var memberlist = Doc.DocumentElement.SelectSingleNode("MemberList");

foreach (XmlNode node in memberlist.ChildNodes)
{
  var nodeElement = node as XmlElement;
  if (nodeElement != null && nodeElement.Name == "NextMemberId")
  {
    nodeElement.SetAttribute("Value", memberId.ToString());
  }
}

Thanks for any inspiration!

Upvotes: 4

Views: 52

Answers (2)

har07
har07

Reputation: 89285

The correct path to get NextMemberId from File according to your sample XML would be :

var nodeElement = Doc.DocumentElement.SelectSingleNode("MemberList/NextMemberId");
nodeElement.SetAttribute("Value", memberId.ToString());

If there are multiple NextMemberId in your actual XML, and you need to filter by Value attribute, then you can add an XPath predicate similar to what the other answer suggested :

var nodeElement = Doc.DocumentElement.SelectSingleNode("MemberList/NextMemberId[@Value=51");

Notice that you can choose to keep or leave single-quotes around 51 depending on whether you want compare the Value as a string or a number, respectively.

Upvotes: 2

Darjan Bogdan
Darjan Bogdan

Reputation: 3900

You can select single node with specified attribute like this:

var nextMemberIdNode = Doc.DocumentElement.SelectSingleNode("NextMemberId[@Value='51']")

Upvotes: 1

Related Questions