Reputation: 7306
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?
Upvotes: 4
Views: 10525
Reputation: 1039140
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; }
}
Upvotes: 5
Reputation: 6270
Easiest way is to make a books class that contains a title property.
public class booksType
{
public string title {get;set;}
}
And the use that as a type for a books property in the main class.
public booksType books {get;set;}
Upvotes: 1
Reputation: 2709
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>
.
Upvotes: 3