0

I am trying to change an existing attribute value of an XML Node that has child nodes. I am getting an exception when trying to do this.

string specificOwnerPath = "Owners/Owner[@id='" + startingOwnerName + startingOwnerZipCode + "']";
XmlNode ownerID = doc.SelectSingleNode(specificOwnerPath);
ownerID.Attributes["id"].Value = ownerNameTextBox.Text + ownerZipCodeTextBox.Text;

The exception I am getting says 'Object reference not set to the instance of an object and is occurring at the final line of code shown above. Does anyone have any suggestions on what I am doing wrong?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1546315
  • 683
  • 5
  • 16
  • 27
  • Almost all cases of NullReferenceException are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Nov 12 '12 at 18:49

2 Answers2

2

Add a check

if (ownerID != null)

to before the last line. Most probably your XPath is not correct (or there simply isn't any matching element).

Knaģis
  • 20,827
  • 7
  • 66
  • 80
-1

if (ownerID != null)

Xpath is not correct in last line

Rahul Jawa
  • 34
  • 1
  • It is not useful to duplicate existing answers. Please only post an answer if you something new to add and can provide a detailed explanation of what that is and how it will specifically answer the question. – Peter Duniho Apr 25 '21 at 16:54