Search code examples
c#xmlxmldocument

XmlDocument how to insert new record into an existing XML File


i have followed few example online with no luck , not sure what's wrong with my code.

I already have xml File and i load it into my program and has some record as

<RETS>
  <Servers>
    <serverInfo type="Type1" LoginString="http://rets.Login" LoginUserName="Ret124" LoginPassword="Mypassword" RetsVersion="RETS/1.5"/>
    </Servers>
  <SearchStrings>
    <search type="Type1"><![CDATA[http://rets2_3/GetMetadata]]></search>
  </SearchStrings>  
</RETS>

Then I let the user add new Record and it should look like this = serverInfo type="Type2" LoginString="http:www.xml.com" LoginUserName="Re34555" etc

XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("RETSDictionary.xml");
            XmlNode node = xmlDoc.SelectSingleNode("RETS/Servers/serverInfo");
            node.Attributes["type"].Value = m_type; // these values coming for text field 
            node.Attributes["LoginString"].Value = m_loginString;
            node.Attributes["LoginPassword"].Value = m_loginPassword;
            node.Attributes["LoginUserName"].Value = m_loginUserName;
            node.Attributes["RetsVersion"].Value = m_retsVersion;


            try {
                xmlDoc.Save("RETSDictionary.xml");
                m_isSuccessful = true;
                m_message = "New RETS Server saved.";
            }
            catch (Exception ex) {
                m_isSuccessful = false;
                m_message = ex.Message;
            }

so when it hits save nothing happens !


Solution

  • Try creating a new element, and then appending it to the Servers node.

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("RETSDictionary.xml");
    XmlNode serversNode = xmlDoc.SelectSingleNode("RETS/Servers");
    XmlElement node = xmlDoc.CreateElement("serverInfo");
    node.SetAttribute("type", m_type); // these values coming for text field 
    node.SetAttribute("LoginString", m_loginString);
    node.SetAttribute("LoginPassword", m_loginPassword);
    node.SetAttribute("LoginUserName", m_loginUserName);
    node.SetAttribute("RetsVersion", m_retsVersion);
    serversNode.AppendChild(node);