很多人都在谈论 XML,这是一个好主意。但是,如果您可以使用 Linq,您应该真的考虑使用 Linq to XML 而不是 SAX/DOM 解析。
与 SAX 和 DOM 解析器相比,Linq to XML 更容易解析、创建和编辑 XML 文件。使用 SAX/DOM 解析通常需要大量循环才能到达正确的元素或通过节点导航。
来自 MSDN 的示例:
使用 DOM 解析:
XmlDocument doc = new XmlDocument();
XmlElement name = doc.CreateElement("Name");
name.InnerText = "Patrick Hines";
XmlElement phone1 = doc.CreateElement("Phone");
phone1.SetAttribute("Type", "Home");
phone1.InnerText = "206-555-0144";
XmlElement phone2 = doc.CreateElement("Phone");
phone2.SetAttribute("Type", "Work");
phone2.InnerText = "425-555-0145";
XmlElement street1 = doc.CreateElement("Street1");
street1.InnerText = "123 Main St";
XmlElement city = doc.CreateElement("City");
city.InnerText = "Mercer Island";
XmlElement state = doc.CreateElement("State");
state.InnerText = "WA";
XmlElement postal = doc.CreateElement("Postal");
postal.InnerText = "68042";
XmlElement address = doc.CreateElement("Address");
address.AppendChild(street1);
address.AppendChild(city);
address.AppendChild(state);
address.AppendChild(postal);
XmlElement contact = doc.CreateElement("Contact");
contact.AppendChild(name);
contact.AppendChild(phone1);
contact.AppendChild(phone2);
contact.AppendChild(address);
XmlElement contacts = doc.CreateElement("Contacts");
contacts.AppendChild(contact);
doc.AppendChild(contacts);
使用 Linq to XML:
XElement contacts =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144",
new XAttribute("Type", "Home")),
new XElement("phone", "425-555-0145",
new XAttribute("Type", "Work")),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)
)
);
更容易操作,更清晰。
编辑:
将 XML 树保存到 contacts.xml :
// using the code above
contact.Save("contacts.xml");
加载contacts.xml文件:
//using the code above
XDocument contactDoc = XDocument.Load("contacts.xml");
要更新树的元素,doc 中有一些函数可以根据您的需要执行此操作