I have a simple class in C# that I have setup to serialize to XML by using the XmlSerializer class.
[Serializable, XmlRoot("dc", Namespace= dc.NS_DC)]
public class DCItem {
// books??
[XmlElement("title")]
public string Title { get; set; }
}
DCItem serializes great as the code is setup right now (as seen above); however, I would like to change the property "Title" so that it is contained within a "Books" node. For example:
<dc>
<books>
<title>Joe's Place</title>
</books>
</dc>
What's the best way to go about doing this?
You could define a Books class:
public class Books
{
[XmlElement("title")]
public string Title { get; set; }
}
and then:
[XmlRoot("dc", Namespace= dc.NS_DC)]
public class DCItem
{
[XmlElement("books")]
public Books Books { get; set; }
}
Also notice that I have gotten rid of the Serializable attribute which is used by binary serializers and completely ignored by the XmlSerializer class.
Now since I suspect that you could have multiple books:
<dc>
<books>
<title>Joe's Place</title>
<title>second book</title>
<title>third book</title>
</books>
</dc>
you could adapt your object model to match this structure:
[XmlRoot("dc", Namespace= dc.NS_DC)]
public class DCItem
{
[XmlElement("books")]
public Books Books { get; set; }
}
public class Books
{
[XmlElement("title")]
public Book[] Items { get; set; }
}
public class Book
{
[XmlText]
public string Title { get; set; }
}
I am assuming that you want several <title>
under <books>
. Then this is one way of doing it:
[XmlType("title")]
public class Title
{
[XmlText]
public string Text { get; set; }
}
[XmlRoot("dc")]
public class DCItem
{
[XmlArray("books")]
public List<Title> Books { get; set; }
}
You may want to have a <book>
element instead though and put title as an attribute or element on <book>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With