using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using Abp.Collections.Extensions;
using Abp.Extensions;
using Abp.Xml.Extensions;
namespace Abp.Localization.Dictionaries.Xml
{
///
/// This class is used to build a localization dictionary from XML.
///
///
/// Use static Build methods to create instance of this class.
///
public class XmlLocalizationDictionary : LocalizationDictionary
{
///
/// Private constructor.
///
/// Culture of the dictionary
private XmlLocalizationDictionary(CultureInfo cultureInfo)
: base(cultureInfo)
{
}
///
/// Builds an from given file.
///
/// Path of the file
public static XmlLocalizationDictionary BuildFomFile(string filePath)
{
try
{
return BuildFomXmlString(File.ReadAllText(filePath));
}
catch (Exception ex)
{
throw new AbpException("Invalid localization file format! " + filePath, ex);
}
}
///
/// Builds an from given xml string.
///
/// XML string
public static XmlLocalizationDictionary BuildFomXmlString(string xmlString)
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
var localizationDictionaryNode = xmlDocument.SelectNodes("/localizationDictionary");
if (localizationDictionaryNode == null || localizationDictionaryNode.Count <= 0)
{
throw new AbpException("A Localization Xml must include localizationDictionary as root node.");
}
var cultureName = localizationDictionaryNode[0].GetAttributeValueOrNull("culture");
if (string.IsNullOrEmpty(cultureName))
{
throw new AbpException("culture is not defined in language XML file!");
}
var dictionary = new XmlLocalizationDictionary(CultureInfo.GetCultureInfo(cultureName));
var dublicateNames = new List();
var textNodes = xmlDocument.SelectNodes("/localizationDictionary/texts/text");
if (textNodes != null)
{
foreach (XmlNode node in textNodes)
{
var name = node.GetAttributeValueOrNull("name");
if (string.IsNullOrEmpty(name))
{
throw new AbpException("name attribute of a text is empty in given xml string.");
}
if (dictionary.Contains(name))
{
dublicateNames.Add(name);
}
dictionary[name] = (node.GetAttributeValueOrNull("value") ?? node.InnerText).NormalizeLineEndings();
}
}
if (dublicateNames.Count > 0)
{
throw new AbpException("A dictionary can not contain same key twice. There are some duplicated names: " + dublicateNames.JoinAsString(", "));
}
return dictionary;
}
}
}