Reputation: 15
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 !
Upvotes: 0
Views: 720
Reputation: 22311
It is better to use LINQ to XML. This API exists already for more than ten years. And it superseded previous .Net Framework XML APIs.
c#
void Main()
{
const string fileName = @"e:\temp\RETSDictionary.xml";
XDocument xdoc = XDocument.Load(fileName);
// compose new fragment
XElement fragment = new XElement("serverInfo",
new XAttribute("type", "Type2"),
new XAttribute("LoginString", "2222.Login"),
new XAttribute("LoginUserName", "tyy"),
new XAttribute("LoginPassword", "Mypassword2"),
new XAttribute("RetsVersion", "RETS/1.5")
);
// add new fragment to a proper location
xdoc.Descendants("Servers").LastOrDefault().Add(fragment);
// save back to XML file
xdoc.Save(fileName);
}
Output
<RETS>
<Servers>
<serverInfo type="Type1" LoginString="http://rets.Login" LoginUserName="Ret124" LoginPassword="Mypassword" RetsVersion="RETS/1.5" />
<serverInfo type="Type2" LoginString="2222.Login" LoginUserName="tyy" LoginPassword="Mypassword2" RetsVersion="RETS/1.5" />
</Servers>
<SearchStrings>
<search type="Type1"><![CDATA[http://rets2_3/GetMetadata]]></search>
</SearchStrings>
</RETS>
Upvotes: 0
Reputation: 802
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);
Upvotes: 1