XML文件读写学习

 .NET 通过两种方式把 XML 数据写入文件:

  • 可以在内存中使用 XmlDocument 或 XDocument 类创建文档,结束时把它写入文件。
  • 用 XmlTextWrite 直接把文档写入流。在你写数据的时候会逐个节点输出数据。
  • 上述 3 个类都允许把信息写入任意的流,因此XML数据也可以写入到其他存储位置,如数据库中文本类型字段。

读取 XML 文件

  • 可以使用 XmlDocument、XPathNavigator(只读)、XDocument 类一次性将文档加载到内存中。
  • XmlTextReader 类(基于流的读取器),每次读取文档的一个节点。

       基于流的方法减少了内存负担,但如果对 XML 文档执行耗时任务或为了不影响别人访问这个XML文档,还是选择在内存中操作的方式较好。

基于内存的Xml处理:

对内存中的 XML 的处理则更加方便,但没有单一、标准的方式。如下所有的类都支持对 XML 的读取和导航:

  • XmlDocument :它是 XML 数据的标准化接口,但对时间要求比较多。
  • XPathNavigator :它提供比 XML DOM 稍快、更有效的模型,并增强了一些搜索功能,但不能修改或保存 XML 。
  • XDocument :为处理 XML 提供一个更直观和有效的 API。从技术上讲,它是 LINQ to XML 的一部分,但即使没有 LINQ 查询,它也很有用。
 1 XmlDocument xmlDoc = new XmlDocument(); //建立Xml的定义声明

 2             XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "GB2312", null);

 3             xmlDoc.AppendChild(dec);

 4             //创建根节点

 5             XmlNode root = xmlDoc.CreateElement("Map");

 6             xmlDoc.AppendChild(root);

 7 

 8             ILayer player = axMapControl1.get_Layer(0);

 9             IFeatureLayer pfeatlayer = player as IFeatureLayer;

10 

11             XmlElement book = xmlDoc.CreateElement(player.Name);

12             book.SetAttribute("ShapeType", pfeatlayer.FeatureClass.ShapeType.ToString());

13             book.SetAttribute("DataSource", pfeatlayer.FeatureClass.FeatureType.ToString());

14             IGeoFeatureLayer pgeo = pfeatlayer as IGeoFeatureLayer;

15             IFeatureRenderer ren = pgeo.Renderer as IFeatureRenderer;

16             IPersistStream stream = ren as IPersistStream;

17 

18             ESRI.ArcGIS.esriSystem.IMemoryBlobStream pMemoryBlobStream = new ESRI.ArcGIS.esriSystem.MemoryBlobStreamClass();

19 

20             IObjectStream pObjectStream = new ObjectStreamClass();

21             pObjectStream.Stream = pMemoryBlobStream;

22             IPersistStream pPersistStream = (IPersistStream)ren;

23             pPersistStream.Save((IStream)pObjectStream, 0);

24             pMemoryBlobStream.SaveToFile(@"Data\fox.render");

25 

26             XmlElement title = xmlDoc.CreateElement("Symbol");

27             title.InnerText = @"Data\fox.render";

28             book.AppendChild(title);

29             XmlElement symType = xmlDoc.CreateElement("SymbolType");

30             symType.InnerText = ren.GetType().Name;

31             book.AppendChild(symType);

32             

33             root.AppendChild(book);

34             xmlDoc.Save("Map.xml");

参考文献:

http://www.cnblogs.com/SkySoot/archive/2012/08/24/2654336.html

http://www.cnblogs.com/SkySoot/archive/2012/08/27/2658160.html

你可能感兴趣的:(文件读写)