XDocument
是 .NET Framework 中用于表示和操作 XML 文档的类之一,它属于 System.Xml.Linq
命名空间。XDocument
类提供了一种简洁而灵活的方式来创建、加载、操作和保存 XML 文档。
下面是一些 XDocument
类的常见用法:
创建一个新的 XML 文档:
XDocument doc = new XDocument(
new XElement("root",
new XElement("child1", "value1"),
new XElement("child2", "value2")
)
);
从文件加载 XML 文档:
//默认去项目bin/debug目录下去找path_to_xml_file.xml
XDocument doc = XDocument.Load("path_to_xml_file.xml");
从字符串加载 XML 文档:
//这个xmlString可能来自于网络或者别人传输过来的
//如果在本地想用这个方法的话可以用string xmlString = File.ReadAllText(filePath);
//读取本地路径的文件所有内容然后转换成string字符串再使用这个方法读取xml
string xmlString = "<root><child>value</child></root>";
XDocument doc = XDocument.Parse(xmlString);
遍历 XML 元素并读取值:
foreach (XElement element in doc.Descendants("child"))
{
Console.WriteLine(element.Value);
}
修改 XML 文档并保存到文件:
doc.Root.Add(new XElement("newChild", "newValue"));
doc.Save("path_to_save_modified_xml_file.xml");