XmlDocument如何将新记录插入到现有的XML文件中



我在网上学习了几个例子,但运气不佳,不确定我的代码出了什么问题。

我已经有了xml文件,我把它加载到我的程序中,并有一些记录

<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>

然后我让用户添加新的记录,它应该是这样的=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;
}

所以当它点击保存时,什么都不会发生!

尝试创建一个新元素,然后将其附加到Servers节点。

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);

最好使用LINQ to XML。这个API已经存在十多年了。它取代了以前的。Net Framework XML API。

c#

void Main()
{
const string fileName = @"e:tempRETSDictionary.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);
}

输出

<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>

最新更新