如何使用.net中的Windows应用程序将数据插入xml文件?

时间:2009-09-10 04:36:28

标签: c# xml

如何使用.net中的Windows应用程序将数据插入xml文件?

5 个答案:

答案 0 :(得分:1)

有很多关于在.NET here中使用DOM的文档。

您是否有一个具体的例子说明您要做什么?这样你就会得到一个更清晰的答案/例子。

答案 1 :(得分:1)

这是一个非常普遍的问题。有几种常见的方法,具体取决于您的目标用例。

答案 2 :(得分:0)

如果您的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确实会损害你的应用程序的性能。我建议使用XmlReaderXmlWriterXDocument的组合。

答案 3 :(得分:0)

如果您知道XML的架构(XSD),则可以使用xsd.exe生成类来解析这些XML文件。如果您不知道架构,xsd.exe可以尝试为您推断它。

然后很容易向生成的类添加属性(修改原始Schema!)或使用现有属性插入/更改所需的属性。这是执行任务的快速方法。

如果Schema不是太复杂,我会使用XmlSerialization属性手动读/写,因为代码肯定会更清晰。只要XML不使用混合模式等功能,它就可以工作(XML序列化框架有一些限制,如果你坚持良好实践,通常并不重要)

答案 4 :(得分:-1)

这是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();

你可以找到一篇好文章 - Working with XML files in C#

相关问题