简体   繁体   English

C#中的XmlElement

[英]XmlElement in C#

I have a simple class in C# that I have setup to serialize to XML by using the XmlSerializer class. 我在C#中有一个简单的类,我已经设置了使用XmlSerializer类序列化为XML。

[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); DCItem序列化很好,因为代码现在正在设置(如上所示); however, I would like to change the property "Title" so that it is contained within a "Books" node. 但是,我想更改属性“Title”,以便它包含在“Books”节点中。 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: 您可以定义Books类:

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. 另请注意,我已经摆脱了二进制序列化程序使用的Serializable属性,并被XmlSerializer类完全忽略。

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> . 我假设你想要<books>下的几个<title> <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> . 您可能希望使用<book>元素,并将title作为属性或元素放在<book>

Easiest way is to make a books class that contains a title property. 最简单的方法是制作包含title属性的books类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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