LINQ之路二:TO XML(1)
参考微软文档:
https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-overview xml基础
//命名空间
using System.Xml.Linq;
private static void GenerateXmlFile()
{
string xmlPath = @"d:\my.xml";
try
{
//定义一个XDocument结构
XDocument myXDoc = new XDocument(
new XElement("Users",
new XElement("User", new XAttribute("ID", "111111"),new XAttribute("Upwd","123"),
new XElement("name", "EricSun"),
new XElement("password", "123456"),
new XElement("description", "Hello I'm from Dalian")
),
new XElement("User", new XAttribute("ID", "222222"), new XAttribute("Upwd", "456"),
new XElement("name", "Ray"),
new XElement("password", "654321"),
new XElement("description", "Hello I'm from Jilin")
)
)
);
//保存此结构(即:我们预期的xml文件)
myXDoc.Save(xmlPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

读取xml
XDocument employeeDoc = new XDocument(
new XElement("Employees",
new XElement("Employee",
new XElement("Name","小明"),
new XElement("Age",18),
new XElement("Phone", 110),
new XElement("Phone", 120)
),
new XElement("Employee",
new XElement("Name", "小红"),
new XElement("Age", 19),
new XElement("Phone", 119)
)
)
);
// employeeDoc.Save("employee.xml");
//XDocument el = XDocument.Load("employee.xml");
XElement root = employeeDoc.Element("Employees");
IEnumerable<XElement> employees = root.Elements();
foreach(XElement emp in employees)
{
XElement empNodeName = emp.Element("Name");
Console.WriteLine(empNodeName.Value);
//遍历
IEnumerable<XElement> empNodePhones = emp.Elements("Phone");
foreach(XElement phone in empNodePhones)
{
Console.WriteLine(" {0}", phone.Value);
}
}
Console.ReadKey();

常用方法

例如上面的:XElement root = employeeDoc.Element("Employees");获取根元素在此后面追加一个元素: root.Add(new XElement("Employee"));
使用xml特性,增加属性
XDocument xd = new XDocument(
new XElement("root",
new XAttribute("color","red"),
new XAttribute("size", "large"),
new XElement("first",
new XElement("second","1"),
new XComment("只是一条备注")
)
)
);
XElement root = xd.Element("root");
//增加属性
root.SetAttributeValue("size", "medium");//修改属性
root.SetAttributeValue("width", "narrow");//增加属性
XAttribute color = root.Attribute("color");
xd.Save("xd.xml");
Console.WriteLine(color.Value);


浙公网安备 33010602011771号