Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Array without root element

I'm trying to get to this result while serializing XML

<Test>
  <Category>
    <FileName>C:\test.txt</FileName>
    <!-- Note that here this is an array of a simple class with two fields 
         without root -->
    <Prop1>1</Prop1>
    <Prop2>2</Prop2>

    <Prop1>4</Prop1>
    <Prop2>5</Prop2>
    <!-- End array -->
  </Category>
</Test>

I already try different things like this

[Serializable]
[XmlRoot("Test")]
public class Test
{
    [XmlElement("Category")]
    public List<Category> Category= new List<Category>();
}

[Serializable]
[XmlRoot("Category")]
public class Category
{
    [XmlElement("FileName")]
    public string FileName { get; set; }

    [XmlElement("Property")]
    public List<Property> Properties = new List<Property>();
}

[Serializable]
public class Property
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

But I still get this output:

<Test>
  <Category>
    <FileName>C:\test.txt</FileName>
    <Property>
      <Prop1>1</Prop1>
      <Prop2>2</Prop2>
    </Property>
    <Property>
      <Prop1>4</Prop1>
      <Prop2>5</Prop2>
    </Property>
  </Category>
</Test>

How can I remove the Property tag ?? Thanks a lot in advance

like image 496
Khoumbe Avatar asked Jan 23 '11 15:01

Khoumbe


2 Answers

In case if you really need the exact output, as specified above, you can use workaround like this:

[Serializable]
public partial class Test {
    public List<Category> Category;
}

[Serializable]
public partial class Category {
    [XmlElement("FileName")]
    public string FileName;

    [XmlElement("Prop1")]
    [XmlElement("Prop2")]
    [XmlChoiceIdentifier("propName")]
    public string[] Properties;

    [XmlIgnore]
    public PropName[] propName;
}

public enum PropName {
    Prop1,
    Prop2,
}
like image 170
andrey.ko Avatar answered Sep 24 '22 17:09

andrey.ko


No, that is not possible without making things complex. One option is to implement IXmlSerializable, which is hard to get 100% right. You might also be able to so it by creating two subtypes, using the type-based versions of [XmlArrayItem], and hacking the model to pieces. Frankly I don't think that is worth it either.

My personal preference here would be to either choose a different layout, or use LINQ-to-XML. This is not a good it for XmlSerializer.

like image 43
Marc Gravell Avatar answered Sep 24 '22 17:09

Marc Gravell