Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlElement in C#

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?

like image 518
Jagd Avatar asked Jan 15 '23 12:01

Jagd


2 Answers

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; }
}
like image 171
Darin Dimitrov Avatar answered Jan 24 '23 15:01

Darin Dimitrov


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>.

like image 25
odyss-jii Avatar answered Jan 24 '23 14:01

odyss-jii