I am posting an example of how to read an xml from disk and deserializes it to a class.
This way you do not have to be picking up each item manually.
This works on an old project that I have here.
Let's go for the explanations of usage.
This is the template for my xml example.
<Pages>
<Page>
<Name>Page 1</Name>
<Url>http://www.google.com</Url>
<XPathExpression></XPathExpression>
</Page>
<Page>
<Name>Page 2</Name>
<Url></Url>
<XPathExpression></XPathExpression>
</Page>
</Pages>
This is a class I use to load xml, serialize it and deserialize it.
public class UtilXML
{
//Private fields
//Public fields
public XmlDocument XmlDocument { get; set; }
public UtilXML() { }
public void LoadXMLByPath(string FilePath)
{
try
{
XmlDocument = new XmlDocument();
XmlDocument.Load(FilePath);
}
catch (System.Xml.XmlException e)
{
throw new System.Xml.XmlException(e.Message);
}
}
public void SerializeToXml<T>(T obj, string FileName)
{
XmlSerializer XmlSerializer = new XmlSerializer(typeof(T));
FileStream FileStream = new FileStream(FileName, FileMode.Create);
XmlSerializer.Serialize(FileStream, obj);
FileStream.Close();
}
public T DeserializeFromXml<T>(string StringXML)
{
T Result;
XmlSerializer XmlSerializer = new XmlSerializer(typeof(T));
using (TextReader TextReader = new StringReader(StringXML))
{
Result = (T)XmlSerializer.Deserialize(TextReader);
}
return Result;
}
}
Essas são as classes que representam meu xml. Repare nos atributos que decoram essa classe. Eles tem os mesmos nomes dos elementos do xml.
[XmlRoot("Pages")]
public sealed class Pages
{
[XmlElement("Page")]
public List<Page> Items { get; set; }
public Pages()
{
Items = new List<Page>();
}
}
public sealed class Page
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Url")]
public string Url { get; set; }
[XmlElement("XPathExpression")]
public string XPathExpression { get; set; }
}
Usage example:
Upload xml
UtilXML.LoadXMLByPath(@"C:\temp\Pages.xml");
Deserialize to the Pages class.
Pages = this.UtilXML.DeserializeFromXml<Pages>(this.UtilXML.XmlDocument.InnerXml);