C#操作xml文件

事出有因:项目中需要对xaml文件进行排版上的优化,有很多细枝末节的小东西,如果手动一个一个去调(特别是grid中对row和column逐项调整简直要了亲命),故研究了怎么用程序去调整xaml文件。

我的理解,xaml文件就是一种xml文件,只是好像标签<></>之间不会放东西,直接采用标签属性就可以了。C#有标准的操作xml的库,都在System.xml包中。故使用之。

 1         XmlReaderSettings settings = new XmlReaderSettings();
 2             settings.IgnoreComments = true; //注释亦会被当做结点,故在读取的时候忽略掉注释
 3             XmlReader reader = XmlReader.Create("a.xaml", settings);
 4 
 5             XmlDocument doc = new XmlDocument();
 6             doc.Load(reader);
 7 
 8             //注意啦:很多xaml文件会使用命名空间(命名空间是xaml文件中,xmlns=XXX...,其中XXX...就是命名空间
 9             //使用命名空间的话需要将命名空间传入后面的SelectSingleNode的参数中去,不然解析不出正确的结点
10             XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
11             nsMgr.AddNamespace("ns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
12 
13             //来看看Xpath的表达方式 命名空间:某标签[@属性约束条件]
14             XmlNode curr = doc.SelectSingleNode("//ns:Grid[@Name='gridBase']",nsMgr);
15            
16             foreach(var eachNode in curr.ChildNodes){
17                 XmlElement node = (XmlElement)eachNode;
18               
19                 //对node可以尽情调戏啦啦啦
20                 //node.GetAttribute(attributeName) 获取某个属性值
21                 //node.SetAttribute(attributeName , attributeValue) Set某个属性值
22             
23             }

常用的xml文件的操作类应该都在这里面了,使用下来使得界面的优化工作变得轻松多了。NICE。我是程序小赢家啦啦啦啦~

原文地址:https://www.cnblogs.com/glamourousGirl/p/4756081.html