[英]How i insert data into xml file using Windows Application in .net?
如何使用.net中的Windows應用程序將數據插入xml文件?
有文件的有關在.NET中的DOM工作非常好位在這里 。
您是否有要執行的操作的特定示例? 這樣,您將獲得更清晰的答案/示例。
這是一個非常普遍的問題。 有幾種常見方法,具體取決於您的目標用例。
如果您的xml文件不是很大,那么最簡單的選擇之一就是使用XmlDocument 。 只需加載xml並將新的xml節點附加到xml文件中所需的位置即可。
這里是有關XmlDocument的文檔: MSDN 。
代碼示例:
XmlDocument dom = new XmlDocument();
dom.Load("filename");
//Append a new node
XmlElement newNode = dom.CreateElement("NewNode");
dom.DocumentElement.AppendChild(newNode);
每個XmlNode (XmlElement,XmlAttribute,XmlText等)在插入,插入,追加,刪除xml節點之前都有不同的方法。 因此,您可以使用DOM進行幾乎所有操作。
在這種情況下,您的xml文件很大,XmlDocument確實會損害應用程序的性能。 我建議結合使用XmlReader和XmlWriter或XDocument 。
如果您知道XML的架構(XSD),則可以使用xsd.exe生成類來解析這些XML文件。 如果您不知道該架構,則xsd.exe可以嘗試為您外推該架構。
然后,很容易將屬性添加到生成的類中(修改原始Schema!),或使用現有屬性來插入/更改所需的內容。 這是執行任務的快速方法。
如果Schema不太復雜,我將使用XmlSerialization屬性手動進行讀/寫,因為代碼肯定會更干凈。 只要XML不使用混合模式之類的功能,它就可以工作(XML序列化框架中存在一些限制,如果您遵循良好做法,通常並不重要)
這是C#的一個
//The path to our config file
string path = "Config.xml";
//create the reader filestream (fs)
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Create the xml document
System.Xml.XmlDocument CXML = new System.Xml.XmlDocument();
//Load the xml document
CXML.Load(fs);
//Close the fs filestream
fs.Close();
// create the new element (node)
XmlElement newitem = CXML.CreateElement("Item");
// Put the value (inner Text) into the node
newitem.InnerText = "This is item #" + (CXML.DocumentElement.ChildNodes.Count + 1).ToString() + "!";
//Insert the new XML Element into the main xml document (CXML)
CXML.DocumentElement.InsertAfter(newitem, CXML.DocumentElement.LastChild);
//Save the XML file
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
CXML.Save(WRITER);
//Close the writer filestream
WRITER.Close();
您可以找到一篇不錯的文章- 在C#中使用XML文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.