我加入XML文件在我的Windows应用程序,我想添加值从文本框.. 我用下面的代码,如何将xml数据插入到c#中现有的xml中?
string path = "codedata.xml";
XmlDocument doc = new XmlDocument();
if (!System.IO.File.Exists(path))
{
//Create neccessary nodes
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is an XML Generated File");
doc.AppendChild(declaration);
doc.AppendChild(comment);
}
else //If there is already a file
{
// //Load the XML File
doc.Load(path);
}
//Get the root element
XmlElement root = doc.DocumentElement;
XmlElement Subroot = doc.CreateElement("data");
XmlElement Companycode = doc.CreateElement("Companycode");
XmlElement Productcode = doc.CreateElement("Productcode");
XmlElement Productname = doc.CreateElement("Productname");
XmlElement Brandcode = doc.CreateElement("Brandcode");
XmlElement Brandname = doc.CreateElement("Brandname");
Companycode.InnerText = txt_companycode.Text;
Productcode.InnerText = txt_productcode.Text;
Productname.InnerText = txt_productname.Text;
Brandcode.InnerText = txt_brandcode.Text;
Brandname.InnerText = txt_brandname.Text;
Subroot.AppendChild(Companycode);
Subroot.AppendChild(Productcode);
Subroot.AppendChild(Productname);
Subroot.AppendChild(Brandcode);
Subroot.AppendChild(Brandname);
root.AppendChild(Subroot);
doc.AppendChild(root);
//Save the document
doc.Save(path);
//Show confirmation message
MessageBox.Show("Details added Successfully");
它显示附近root.AppendChild(子根)错误;任何人都可以帮助我,我犯了错误。
有什么错误呢? – 2012-07-26 07:03:06
对象引用没有设置为一个实例... – chitra 2012-07-26 07:09:47
LINQ to XML在这种情况下真的很不错:) 你得到这个错误,因为没有'Subroot'的实例尝试添加这一行:'Subroot sub = new Subroot ();'在这行之前''Subroot.AppendChild(Companycode); '并将所有'Subroot'改为'sub' – harry180 2012-07-26 07:53:30