如何在 C# 中通过 XDocument 列出 xml 元素?
我在这里阅读了很多有关 xml 的主题并尝试了一些,但我仍然无法解决这个问题。
我必须从 xml 文件中列出“Items”并将其加载到 ListView 中。我的项目是用 Pocket-PC 制作的。这是示例 xml 内容。
<? xml version="1.0" encoding="utf-8" ?>
<Library>
<Item>
<Name>Picture</Name>
<FullPath>\My Device\My Documents\Picture</FullPath>
<SystemFullpath>\Program Files\Explorer\Library</SystemFullpath>
<Created>0001-01-01T00:00:00</Created>
</Item>
<Item>
<Name>Video</Name>
<FullPath>\My Device\My Documents\Video</FullPath>
<SystemFullpath>\Program Files\Explorer\Library</SystemFullpath>
<Created>0001-01-01T00:00:00</Created>
</Item>
<Item>
<Name>File</Name>
<FullPath>\My Device\My Documents\File</FullPath>
<SystemFullpath>\Program Files\Explorer\Library</SystemFullpath>
<Created>0001-01-01T00:00:00</Created>
</Item>
</Library>
我添加项目的方式:
public bool AddLibrary(Library lib)
{
try
{
XDocument xDoc = XDocument.Load(fileName);
XElement xe = new XElement("Item",
new XElement("Name", lib.Name),
new XElement("Fullpath", lib.Fullpath),
new XElement("SystemFullpath", lib.SystemFullpath),
new XElement("Created", lib.Created));
xDoc.Element("Library").Add(xe);
xDoc.Save(fileName);
return true;
}
catch { return false; }
}
图书馆实体:
public class Library
{
public Library() { }
// Unique
public string Name { get; set; }
public string Fullpath { get; set; }
public string SystemFullpath { get; set; }
public DateTime Created { get; set; }
public List<Items> Items { get; set; }
}
以及检索返回错误的项目的代码:
public List<Library> RetrieveAllLibrary()
{
List<Library> libList = new List<Library>();
if (File.Exists(fileName))
{
XDocument xDoc = XDocument.Load(fileName);
var items = from item in xDoc.Descendants("Item")
select new
{
Name = item.Element("Name").Value,
FullPath = item.Element("FullPath").Value,
Created = item.Element("Created").Value
};
if (items != null)
{
foreach (var item in items)
{
Library lib = new Library();
lib.Name = item.Name;
lib.Fullpath = item.FullPath;
lib.Created = DateTime.Parse(item.Created);
libList.Add(lib);
}
}
}
return libList;
}
错误说:
我希望我能很好地解释它。感谢您的帮助!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是这一行:
名称是用小写“p”输入的,后来您使用了带有大写“P”的
"FullPath"
。如果您想保留数据,还应该将 XML 文件中的所有“Fullpath”替换为“FullPath”。
Your problem is this line:
The name is typed with a lower case "p", and later you used
"FullPath"
with a capital "P".You should also replace all "Fullpath" with "FullPath" in the XML-file, if you want to keep the data.