C#, XML, adding new nodes

Your first problem is that the node names in your XPath don’t match those of the XML. XML is case sensitive, so you need to use Root, not root:

XmlNode root = xmldoc.SelectSingleNode("/ns:Root/ns:profesori", nsMgr);

Next, instead of xmldoc.NamespaceURI, use the actual namespace uri:

string strNamespace= "http://prpa.org/XMLSchema1.xsd";
nsMgr.AddNamespace("ns", strNamespace);

or do this:

string strNamespace= xmldoc.DocumentElement.NamespaceURI;
nsMgr.AddNamespace("ns", strNamespace);

The NamespaceURI of an XmlDocument object will always be an empty string.

And you should also use this namespace when creating your elements:

XmlNode prof = xmldoc.CreateNode(XmlNodeType.Element, "profesor", strNamespace);

XmlNode ime = xmldoc.CreateNode(XmlNodeType.Element, "ime", strNamespace);
ime.InnerText = name;
prof.AppendChild(ime);

XmlNode prezime = xmldoc.CreateNode(XmlNodeType.Element, "prezime", strNamespace);
prezime.InnerText = surname;
prof.AppendChild(prezime);

root.AppendChild(prof);

You might also consider using the CreateElement() method, which would be slightly shorter:

XmlNode prof = xmldoc.CreateElement("profesor", strNamespace);

Or, my preference would be to use an XmlWriter:

using(XmlWriter writer = root.CreateNavigator().AppendChild())
{
    writer.WriteStartElement("profesor", strNamespace);
    writer.WriteElementString("ime", strNamespace, name);
    writer.WriteElementString("prezime", strNamespace, surname);
    writer.WriteEndElement();
}

Leave a Comment