C#读取带命名空间的xml,xaml文件的解决方案

使用C#读取xml文件有三种常用的方式:

1、xmlDocument

2、XmlTextReader

3、Linq To Xml

但是这些方式在读写有些带命名空间的xml时就不知道怎么办了(例如把xaml文件当作xml文件来读写的时候)。

对于xaml文件,C#虽然能用XamlReader直接把xaml文件转换为对象,但是有的时候我们只是想取得其中一些字段,并不想转换为对象。

本文就以读取xml方式来读写xaml,给大家做一个示范。

其中xaml文件如下所示,文件名为test.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="testkey">testStringInnerText</sys:String>
</ResourceDictionary>

1、读取xaml节点。

 1             XmlDocument xmlDoc = new XmlDocument();
 2             xmlDoc.Load("D:\\test.xaml");
 3 
 4             //添加命名空间,这一步一定要有,否则读取不了
 5             XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
 6             xmlNamespaceManager.AddNamespace("x", "http://schemas.micorsoft.com/winfx/2006/xaml");
 7             xmlNamespaceManager.AddNamespace("sys", "clr-namespace:System;assembly=mscorlib");
 8 
 9 
10             XmlNodeList xmlNodeList = xmlDoc.DocumentElement.ChildNodes;
11             foreach (XmlNode childXmlNode in xmlNodeList)
12             {
13                 //读取数据节点(sys:String)
14                 string childName = childXmlNode.Name;
15                 //读取属性值(testKey)
16                 string childAttributesValue = childXmlNode.Attributes["x:Key"].Value;
17                 //读取节点文本(testStringInnerText)
18                 string childInnerText = childXmlNode.InnerText;
19                 //读取子节点
20                 XmlNodeList childXmlNodeList = childXmlNode.ChildNodes;
21             }

 

2、写入 xaml 节点

 1 var rootXmlDocument=new XmlDocument();
 2  
 3  XmlNode xmlNode=new XmlNode();
 4 //需要在这里生成一个xmlNode节点...
 5 //...
 6 //然后用appendchild方法插入
 7  rootXmlDocument.AppendChild(xmlNode);
 8  XmlElement rootXmlElement=(XmlElement)rootXmlDocument.ChildNodes[0];
 9  
10 //设置命名空间
11  rootXmlElement.SetAttribute("xmlns","http://schemas.microsoft.com/winfx/2006/xaml/presentation");
12  rootXmlElement.SetAttribute("xmlns:x","http://schemas.microsoft.com/winfx/2006/xaml");
13  rootXmlElement.SetAttribute("xmlns:sys","clr-namespace:System;assembly=mscorlib");
14  
15  rootXmlDocument.Save("D:\\test.xaml");

欢迎转载,转载请注明来自Leaco的博客:http://www.cnblogs.com/Leaco/p/3170729.html

posted @ 2013-07-08 23:56  Leaco  阅读(3087)  评论(0编辑  收藏  举报
欢迎各种转载,转载请注明来自 Leaco 的博客:http://www.cnblogs.com/Leaco
Top
关注
收藏
评论