创建xml文档:
XDocument xmlDoc = new XDocument();
//全局的namespace单独定义 会在第一次使用时写入xml
XNamespace xn = "http://xxx1";
xmlDoc.Declaration = new XDeclaration(new XDeclaration("1.0", "utf-8", ""));
XElement root = new XElement(xn+"IndexItem", new XAttribute(XNamespace.Xmlns + "i", "http://xxxx2"));
xmlDoc.Add(root);
root.Add(new XElement(xn+"Path",@"a\1"));
root.Add(new XElement(xn + "Item",
new XElement(xn + "ID", "1213123"),
new XElement(xn + "Information",
new XElement(xn + "Mode"),
new XElement(xn + "Comment", "helloworld"),
new XElement(xn+ "CreatedDate", DateTime.Now.ToUniversalTime()),
new XElement(xn+"User", "admin")),
new XElement(xn+"Name", "New"),
new XElement(xn+"Version", "1.1")));
xmlDoc.Save(@"C:1.xml");
增加一个节点 :
XDocument xmlDoc = XDocument.Load(@"path");
XNamespace xn = "namespace";
//添加
var node = xmlDoc.Root.Element(xn + "target");//定位到节点
node.Add(new XElement(xn + "节点1名",
new XElement(xn + "节点2名", "adasd"),
new XElement(xn + "节点3名", "6888"),
new XElement(xn + "节点4名", @"Cart1\Equipment State")));
xmlDoc.Save(@"path");
去除某一点:
XDocument xmlDoc = XDocument.Load(@"path");
XNamespace xn = "namespace";
var nodelist = xmlDoc.Root.Descendants(xn + "DlpConfigurationItem");
foreach(var node in nodelist)
{
if(node.Element(xn+"Name").Value == @"xx")
{
node.Remove();
break;
}
}
xmlDoc.Save(@"path");