Destroy XML in C # Object

How can I redraw the following CatalogProduct tags to 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 you want to skip this item when returning to deserialization

thank

+3
source share
5 answers
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
        };
+5
source

Just for your information, here is an example of 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);
    }
}
+4
source

, xsd.exe . -, XML :

xsd.exe file.xml .xsd.

:

xsd.exe /c file.xsd .cs.

File.cs (-), XML , , . this.

+1

"CatalogProduct" , , , .net 4.0 , .

, , - XmlSerializer Deserialize, CatalogProduct.

, : http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx

0

, CatalogProduct :

    public class CatalogProduct {
        public string Name;
        public string Version;
    }

, Linq Xml

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();

, .NET true object graph,

0

Source: https://habr.com/ru/post/1773868/


All Articles