Customizable XML Serialization

I am trying to create a class that I can serialize to create the following XML:

<chart palette='1'>
  <categories>
    <category label='2001' />
    <category label='2002' />

.. etc.

I have a class that looks something like this:

[XmlRoot("chart")]
public class Chart
{        
    [XmlAttributeAttribute("palette")]
    public string Palette;

    [XmlElement("categories")]
    public List<Category> Categories = new List<Category>();
}

[XmlRoot("category")]
public class Category
{
    [XmlAttributeAttribute("label")]
    public string Label;
}

However, this does not create the desired chart structure chart-> categories-> category @. The XmlRoot in the Category class does not seem to be used. Here is the result I got from this code:

 <chart palette="2">
  <categories label="2002" /> 
 </chart>

How to get the XML structure I want?

+3
source share
4 answers

Use XmlArrayAttribute and XmlArrayItemAttribute

[XmlRoot("chart")]
public class Chart
{        
    [XmlAttributeAttribute("palette")]
    public string Palette;

    [XmlArray("categories")]
    [XmlArrayItem("category")]
    public List<Category> Categories = new List<Category>();
}


public class Category
{
    [XmlAttributeAttribute("label")]
    public string Label;
}

xml, , xsd.exe . , xsd, .

xsd.exe something.xml
xsd.exe something.xsd /classes

, , , ( xsd xml),

+10

:

[XmlRoot("chart")]
public class Chart
{        
    [XmlAttributeAttribute("palette")]
    public string Palette;

    [XmlArray("categories")]
    [XmlArrayItem("category")]
    public List<Category> Categories = new List<Category>();
}

[XmlRoot("category")]
public class Category
{
    [XmlAttribute("label")]
    public string Label;
}
+6
+1

, ASP.NET,

XML ASP.NET

, , .

, xsd.exe, , Visual Studio ( .NET 2005)

For example, you can create the following schema by passing it an XML file

eg. xsd yourfile.xml

You can then use the generated xsd to create a serialization class, which is basically an XML object model with a class for each node, passing in an xsd schema

eg. xsd yourfile.xsd / c / l: C

Again, this is based on .NET, so apologize if this is not of interest to the original poster.

0
source

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


All Articles