简体   繁体   中英

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?

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

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;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM