天天看點

c語言讀取xml檔案帶命名空間,如何讀寫擁有命名空間xmlns 屬性的Xml檔案(C#實作)...

usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Reflection;usingSystem.Text;usingSystem.Xml;usingSystem.Xml.Linq;namespaceReadXml

{classProgram

{static void Main(string[] args)

{

XmlDocument xmlDoc= newXmlDocument();

XmlReaderSettings settings= newXmlReaderSettings();

settings.IgnoreComments= true;

XmlReader reader= XmlReader.Create("./test.xml");

xmlDoc.Load(reader);

reader.Close();

XmlNamespaceManager xmlNamespaceManager= newXmlNamespaceManager(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 innodeList)

{

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 innodeListAdd)

{

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 innodeListUpdate)

{

Console.WriteLine(item.OuterXml);

}

Console.ReadKey();

}

}

}