Backup/MyFriends/LINQ/XLINQ File Handling/XMLFileOperations.cs
(开头部分) 5KB这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Data.Linq;
using System.Xml.Linq;
using System.Xml;
using System.IO;
namespace MyFriends
{
public class XMLFileOperations
{
public static string XmlFilename { get; set; }
public static List<Friend> GetFriends()
{
string fullXmlPath =//获取当前XML文件的完整路径
System.IO.Path.Combine
(Environment.CurrentDirectory,
XMLFileOperations.XmlFilename);
//使用LINQ to XML语法查询XML文件中的联系人
var xmlFriendResults =
from friend in StreamElements(fullXmlPath, "Friend")
select new Friend
{//将查询结果投影为一个Friend对象
ID = new Guid(friend.Element("ID").Value),
Name = friend.Element("name").SafeValue(),
Email = friend.Element("email").SafeValue(),
PhotoUrl = friend.Element("photo").SafeValue(),
VideoUrl = friend.Element("video").SafeValue(),
MusicUrl = friend.Element("music").SafeValue()
};
//返回所查询的列表
return xmlFriendResults.ToList();
}
public static void CreateInitialFile(string fullXmlPath, Friend friend)
{//创建初始文件
XElement friendsXmlDocument =
new XElement("MyFriends",
new XElement("Friend",
new XElement("ID", friend.ID),
new XElement("name", friend.Name),
new XElement("email", friend.Email),
new XElement("photo", friend.PhotoUrl),
new XElement("video", friend.VideoUrl),
new XElement("music", friend.MusicUrl))
);
//Save方法将XML序列化为指定位置的文件
friendsXmlDocument.Save(fullXmlPath);
}
public static void AppendToFile(string fullXmlPath, Friend friend)
{//追加XML到文件中,Load方法从文件加载XElement
XElement friendsXmlDocument = XElement.Load(fullXmlPath);
//调用XElement对象追加联系人信息
friendsXmlDocument.Add(new XElement("Friend",
new XElement("ID", friend.ID),
new XElement("name", friend.Name),
new XElement("email", friend.Email),
后面还有 55 行代码,解锁后查看完整代码
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
