XML大家一定都很熟悉了,这是一篇关于C# 操作XML的文章

C# 操作XML之建立Xml对象准备工作

C# 操作XML之建立Xml对象要添加的命名空间为 System.Xml  System.Xml.XPath

有时候我们可能需要根据数据库里的数据值生成Xml文件,那么,我们就要在内存里先建立Xml对象,之后再将Xml对象以字符串或文件的形式输出。首先来看看怎么用.Net下的类所提供的方法来生成Xml的各部分

C# 操作XML之建立Xml对象实例:假设一软件商买如下游戏:文明3,帝国时代

那么以下代码将生成如下的Xml文档 

 
  
  1. ﹤?xml version="1.0" encoding="utf-8" ?﹥  
  2. ﹤v:Games xmlns:v="www-shop-game"﹥  
  3.     ﹤v:Game name="文明3"﹥  
  4. ﹤Price﹥100﹤/Price﹥  
  5.     ﹤/Game﹥  
  6.     ﹤v:Game name="帝国时代"﹥  
  7. ﹤Price﹥200﹤/Price﹥  
  8.     ﹤/Game﹥  
  9. ﹤/Games﹥ //C# 操作XML之建立Xml对象
 
  
  1.  XmlDocument xml = new XmlDocument();  
  2. //建立XmlDomcument对象 ,C# 操作XML之建立Xml对象  
  3. XmlDeclaration Declaration = xml.  
  4. CreateXmlDeclaration("1.0""utf-8"null);  
  5. //Xml Declaration(Xml声明)  
  6. XmlNode RootNode = xml.CreateNode(  
  7. XmlNodeType.Element,"v","Games","www-microsoft-game");  
  8. xml.AppendChild(RootNode);  
  9. XmlNode node1 = xml.CreateNode(XmlNodeType.Element,   
  10. "v""Game""www-microsoft-game");  
  11. RootNode.AppendChild(node1);  
  12. node1.Attributes.Append(xml.  
  13. CreateAttribute("name")).InnerText = "文明3";  
  14. node1.AppendChild(xml.CreateNode(  
  15. XmlNodeType.Element,"Price",null)).InnerText = "100";  
  16. XmlNode node2 = xml.CreateNode(  
  17. XmlNodeType.Element, "v""Game""www-microsoft-game");  
  18. RootNode.AppendChild(node2);  
  19. node2.Attributes.Append(xml.  
  20. CreateAttribute("name")).InnerText = "帝国时代";  
  21. node2.AppendChild(xml.CreateNode(  
  22. XmlNodeType.Element, "Price"null)).InnerText = "300";  
  23. xml.InsertBefore(Declaration,   
  24. xml.DocumentElement); 

以上虽是一个很简单的Xml文档,但万变不离其中,只要掌握了方法,再复杂的Xml串也可以拼出来。

C# 操作XML之建立Xml对象的基本内容就向你介绍到这里,希望对你了解和学习C# 操作XML之建立Xml对象有所帮助。