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>开发者_如何学Go;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
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,
}
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
.
精彩评论