Deserialize XML into a C# object
How can I desearlize the below CatalogProduct tags into my CatalogProduct object using C#?
<?xml version="1.0" encoding="UTF-8"?>
<CatalogProducts>
<CatalogProduct Name="MyName1" Version=开发者_如何学运维"1.1.0"/>
<CatalogProduct Name="MyName2" Version="1.1.0"/>
</CatalogProducts>
Note i don't have a CatalogProducts object so want to skip that element when pulling back the into to deserialize
Thanks
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<CatalogProducts>" +
"<CatalogProduct Name=\"MyName1\" Version=\"1.1.0\"/>" +
"<CatalogProduct Name=\"MyName2\" Version=\"1.1.0\"/>" +
"</CatalogProducts>";
var document = XDocument.Parse(xml);
IEnumerable<CatalogProduct> catalogProducts =
from c in productsXml.Descendants("CatalogProduct")
select new CatalogProduct
{
Name = c.Attribute("Name").Value,
Version = c.Attribute("Version").Value
};
Just for your information, here's an example how to really serialize and deserialize an object:
private CatalogProduct Load()
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
using (var xmlReader = new XmlTextReader("CatalogProduct.xml"))
{
if (serializer.CanDeserialize(xmlReader))
{
return serializer.Deserialize(xmlReader) as CatalogProduct;
}
}
}
private void Save(CatalogProduct cp)
{
using (var fileStream = new FileStream("CatalogProduct.xml", FileMode.Create))
{
var serializer = new XmlSerializer(typeof(CatalogProduct));
serializer.Serialize(fileStream, cp);
}
}
The canonical method would be to use the xsd.exe
tool twice. First, to create a schema from your example XML as so:
xsd.exe file.xml
will generate file.xsd.
Then:
xsd.exe /c file.xsd
will generate file.cs.
File.cs will be the object(s) you can deserialize your XML from using any one of the techniques that you can easily find here, e.g. this.
Assuming your CatalogProduct
object looks something like this:
public class CatalogProduct {
public string Name;
public string Version;
}
I think Linq to Xml will be the simplest and fastest way for you
var cps1 = new[] { new CatalogProduct { Name = "Name 1", Version = "Version 1" },
new CatalogProduct { Name = "Name 2", Version = "Version 2" } };
var xml = new XElement("CatalogProducts",
from c in cps1
select new XElement("CatalogProduct",
new XAttribute("Name", c.Name),
new XAttribute("Version", c.Version)));
// Use the following to deserialize you objects
var cps2 = xml.Elements("CatalogProduct").Select(x =>
new CatalogProduct {
Name = (string)x.Attribute("Name"),
Version = (string)x.Attribute("Version") }).ToArray();
Please note that .NET offers true object graph serialization which I have not shown
Without "CatalogProduct" object i think it's very difficult, maybe with the dynamic type of .net 4.0 it's possible, but i'm not sure.
The only way i know, is to utilize the XmlSerializer class with Deserialize method, but you need the object CatalogProduct.
I hope the following link is useful: Link
精彩评论