我们在进行C#项目Xml读写开发时经常遇到一些读写问题,今天我要介绍的是遇到多个命名空间xmlns属性时如何读写此类文件。
比如下面这个Xml文件:
这个文件有一个默认的命名空间:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
还有两个拥有前缀x和d的命名空间:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 这类Xml文件的读写方法如下:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ReadXml
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create("./test.xml");
xmlDoc.Load(reader);
reader.Close();
XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
xmlNamespaceManager.AddNamespace("e", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
xmlNamespaceManager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
xmlNamespaceManager.AddNamespace("d", "http://schemas.microsoft.com/expression/blend/2008");
//读xml
XmlNodeList nodeList = xmlDoc.SelectNodes("e:project/e:root/e:branch/e:leaf", xmlNamespaceManager);
foreach (XmlNode item in nodeList)
{
Console.WriteLine(item.OuterXml);
}
//增加一条leaf
XmlNode xmlNode = xmlDoc.SelectSingleNode("e:project/e:root/e:branch", xmlNamespaceManager);
var ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XmlElement leafElement = xmlDoc.CreateElement("leaf", ns);
leafElement.SetAttribute("Name", "leaf14");
leafElement.SetAttribute("value", "efg");
xmlNode.AppendChild(leafElement);
xmlDoc.Save("./test.xml");
Console.WriteLine("增加一条leaf后:");
XmlNodeList nodeListAdd = xmlDoc.SelectNodes("e:project/e:root/e:branch/e:leaf", xmlNamespaceManager);
foreach (XmlNode item in nodeListAdd)
{
Console.WriteLine(item.OuterXml);
}
//修改一条leaf
XmlNodeList nodeList1 = xmlDoc.SelectNodes("e:project/e:root/e:branch/e:leaf", xmlNamespaceManager);
for (int i = (nodeList1.Count - 1); i >= 0; i--)
{
XmlElement xe = (XmlElement)nodeList1\[i\];
if (xe.GetAttribute("Name") == "leaf11")
{
xe.SetAttribute("Value", "aaa");
}
}
xmlDoc.Save("./test.xml");
Console.WriteLine("修改第一条leaf后:");
XmlNodeList nodeListUpdate = xmlDoc.SelectNodes("e:project/e:root/e:branch/e:leaf", xmlNamespaceManager);
foreach (XmlNode item in nodeListUpdate)
{
Console.WriteLine(item.OuterXml);
}
Console.ReadKey();
}
}
}
程序运行后控制台显示如下:
增加一条leaf后:
修改第一条leaf后:
新的Xml显示如下:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章