// --------------------------------------------------------------------------------------------------------------------
//
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
//
//
// A Helper class to parse plist files.
//
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrakeWPF.Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
///
/// A Helper class to parse plist files.
///
public class PList : Dictionary
{
#region Constructors and Destructors
///
/// Initializes a new instance of the class.
///
public PList()
{
}
///
/// Initializes a new instance of the class.
///
///
/// The file.
///
public PList(string file)
{
this.Load(file);
}
#endregion
#region Public Methods
///
/// Load a plist file.
///
///
/// The file name / path
///
///
/// True if successful, false otherwise.
///
public bool Load(string file)
{
this.Clear();
XDocument doc = XDocument.Load(file);
XElement plist = doc.Element("plist");
if (plist != null)
{
XElement array = plist.Element("array");
if (array != null)
{
XElement dict = array.Element("dict");
if (dict != null)
{
IEnumerable dictElements = dict.Elements();
this.Parse(this, dictElements);
return true;
}
}
}
return false;
}
#endregion
#region Methods
///
/// Parse a list of elements
///
///
/// The dict.
///
///
/// The elements.
///
private void Parse(PList dict, IEnumerable elements)
{
for (int i = 0; i < elements.Count(); i += 2)
{
XElement key = elements.ElementAt(i);
XElement val = elements.ElementAt(i + 1);
dict[key.Value] = this.ParseValue(val);
}
}
///
/// The parse array.
///
///
/// The elements.
///
///
/// The .
///
private List ParseArray(IEnumerable elements)
{
return elements.Select(e => this.ParseValue(e)).ToList();
}
///
/// The parse value.
///
///
/// The XElement.
///
///
/// The parsed value object.
///
private dynamic ParseValue(XElement val)
{
switch (val.Name.ToString())
{
case "string":
return val.Value;
case "integer":
return int.Parse(val.Value);
case "real":
return float.Parse(val.Value);
case "true":
return true;
case "false":
return false;
case "dict":
var plist = new PList();
this.Parse(plist, val.Elements());
return plist;
case "array":
List list = this.ParseArray(val.Elements());
return list;
default:
throw new ArgumentException("This plist file is not supported.");
}
}
#endregion
}
}