我在写一个叫做的类,其类别为,它有两个静态方法用于从外部资源中检索XML数据。在我下面的例子中,我只会展示一个,因为它们非常相似。这个XDocument代码是否安全?
我想知道的是,无论这个代码是无效的URL,无效的数据等等,这个代码是否是“安全的”。基本上使它更加健壮。 这里是德码
private static string XmlUri
{
get { return "path-to-xml-file"; }
}
private static XDocument XmlFile { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public int Parent { get; set; }
/// <summary>
/// Gets a specific category
/// </summary>
/// <param name="id"></param>
/// <returns>A Category with the specified ID</returns>
public static Category Get(int id)
{
try
{
if (XmlFile == null)
XmlFile = XDocument.Load(XmlUri);
}
// Invalid URL or data
catch (Exception ex)
{
// TODO: Log exception
Console.WriteLine(ex.Message);
}
if (XmlFile == null)
return null;
var cat = from category in XmlFile.Descendants("Category")
where category.Attribute("id").Value.ParseSafe() == id
select new Category
{
ID = category.Attribute("id").Value.ParseSafe(),
Parent = category.Attribute("parent").Value.ParseSafe(),
Name = category.Value
};
return cat.SingleOrDefault();
}
您对外部XML有多少控制?您可能需要根据模式对其进行验证。此外,您的代码可能爆炸*(要使用技术术语...)*当多个线程尝试读取XML时。 – ChaosPandion 2011-02-24 21:52:01
@Chaos - 我无法控制XML文件,所以我必须使用我所拥有的。你能不能解释一下线程安全部分,听起来不像我会遇到这种情况,但要确定。谢谢! – Marko 2011-02-25 00:12:30