I’m posting an example of how to read an xml from disk and deserialize it to a class.
This way you don’t have to pick each item manually.
This works on an old project I have here.
Let’s go for the use explanations.
This is the template of 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 the 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; }
}
Example of use:
Load xml
UtilXML.LoadXMLByPath(@"C:\temp\Pages.xml");
Deserialize for the Pages class.
Pages = this.UtilXML.DeserializeFromXml<Pages>(this.UtilXML.XmlDocument.InnerXml);
It is better to paste the code than a screenshot. You can [Edit] the question to include more details. I still have to tag the language too, I don’t know what it is...
– brasofilo
What is the value of
xml
? This variable is null?– carlosfigueira
xml Carlos, will read the file . xml, then create a parser and generate a list of contents in the file.
– Leandrolap
The error occurs in the Xdocument.Parse(xml line)?
– Gus