XML Embedded Resource to Object
2018-04-17 本文已影响0人
Kreiven
You can create an XML file which has configurations, constants or simple data in it, and in its file properties set Build Action
to Embedded Resource
.
Then a related model with XmlAttributes is required.
Notice the differences among
XmlRoot
,XmlAttribue
,XmlElement
, or this will cause parse errors.
TeamModel.cs
[XmlRoot("TeamModel")]
public class TeamModel
{
private string _name = string.Empty;
[XmlAttribute("Name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
private List<MemberModel> aList = new List<MemberModel>();
[XmlElement("Member")]
public List<MemberModel> AList
{
get { return aList; }
set { aList = value; }
}
}
public class MemberModel
{
private string _firstName = string.Empty;
[XmlAttribute("FirstName")]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _lastName = string.Empty;
[XmlAttribute("LastName")]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
TeamModelConfig.xml
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTeamModel >
<TeamModel Name="MyTeam">
<Member FirstName="Zhang" LastName="San"/>
<Member FirstName="Li" LastName="Si"></Member>
</TeamModel>
</ArrayOfTeamModel>
Method for XML parse
public T ParseEmbeddedXml<T>(string resourceName)
{
var result = default(T);
//use reflection to get executing assembly and its name
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
Assembly.GetExecutingAssembly().GetName().Name.ToString()+"."+resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
XmlSerializer xmlSerializer = XmlSerializer.FromTypes(new[] { typeof(T) }).FirstOrDefault();//new XmlSerializer(typeof(T));
var tempResult = xmlSerializer.Deserialize(reader);
if (tempResult is T)
result = (T)tempResult;
}
}
return result;
}