• 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

    欢迎转载,转载请注明来自 Leaco 的博客:http://www.cnblogs.com/Leaco
  • 相关阅读:
    系统吞吐量(TPS)、用户并发量、性能测试概念和公式
    javascript 匿名函数和闭包
    构建高可扩Web架构和分布式系统实战
    Javascript prototype 的作用
    myeclipse下载地址
    tomacat7.0配置(windows)
    IEEE802.11
    C#(多态)
    C#(泛型集合的使用)
    C#(对象引用)
  • 原文地址:https://www.cnblogs.com/Leaco/p/3170729.html
Copyright © 2020-2023  润新知