XMLNode --> Adding an Attribute

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello Guys:

What am I doing wrong with this code? I can't seem to get it to simply add
an attribute to my node. The node already exists. I am simply opening the
XMLDocument and creating one attribute to the document. I am not creating
the document new

XmlNamespaceManager xnsm = new XmlNamespaceManager(xmlFile.NameTable);

xnsm.AddNamespace("a", "http://www.icsm.com/icsmxml");
XmlNode xNode = xmlFile.SelectSingleNode("//a:HeaderShipping", xnsm);

System.Xml.XmlAttribute attribute;
attribute..Name = "accountNumber";
attribute.Value = thirdPartyShipping;

xNode.Attributes.Append(attribute);

Thanks
Andy
 
You didn't say what happeens? Error? No error? If error, what is the
message? Which line is causing the problem?
If no error, what exactly happens vs. what do you expect?

These are all important details!

In any case, your 'attribute' variable is never getting instantiated. So I
would assume the line where you assign the Name property is where you get a
NullReferenceException. That is, if you really only used one dot and not two
when referencing the Name property, otherwise it wouldn't have compiled.
 
Andy said:
Hello Guys:

What am I doing wrong [...]
System.Xml.XmlAttribute attribute;
attribute..Name = "accountNumber";
attribute.Value = thirdPartyShipping;

You need to understand class instances and their creation better.

Declaring a variable of a class type (System.Xml.XmlAttribute)
doesn't create or allocate an object of that type. It only allocates
a reference (which is essentially a pointer that is traced by the
garbage collector) and initializes it with a null reference. You
need to create the object with 'new', as specified by the constructor
which is documented in the class library reference.

HTH/ONI
 
Andy wrote:

What am I doing wrong with this code? I can't seem to get it to simply add
an attribute to my node. The node already exists. I am simply opening the
XMLDocument and creating one attribute to the document. I am not creating
the document new

XmlNamespaceManager xnsm = new XmlNamespaceManager(xmlFile.NameTable);

xnsm.AddNamespace("a", "http://www.icsm.com/icsmxml");
XmlNode xNode = xmlFile.SelectSingleNode("//a:HeaderShipping", xnsm);

The simplest approach is doing e.g.
XmlElement xNode = xmlFile.SelectSingleNode("//a:HeaderShipping",
xnsm) as XmlElement;
xNode.SetAttribute("accountNumber", thirdPartyShipping);

If you really think you need to create the attribute node separately
then use the factory method the XmlDocument instance itself exposes e.g.
XmlAttribute attribute = xmlDocument.CreateAttribute("accountNumber");
attribute.Value = thirdPartyShipping;
XmlElement xNode = xmlFile.SelectSingleNode("//a:HeaderShipping",
xnsm) as XmlElement;
xNode.SetAttributeNode(attribute);
 
Back
Top