c#将二级元素序列化为属性 [英] c# serialize second level element to property
问题描述
我正在尝试创建可序列化的类,但我想将二级元素映射到我的类属性.这样做的最佳方法是什么.
I am trying to create serializable class but I want to map second level element to my property of class. What's the best way of doing this.
示例 xml &班级
Example xml & class
<SearchResult>
<Head>
<Title q="test">My search Result</Title>
</Head>
<Results>
<Result>...</Result>
<Result>...</Result>
<Result>...</Result>
</Results>
</SearchResult>
[Serializable]
[XmlRoot(ElementName = "GSP")]
public class SearchResult
{
**[XmlElement(ElementName=@"Head\Title")]**
public string Title { get; set; }
[XmlArray(ElementName = "Results")]
[XmlArrayItem(ElementName = "Result")]
public List<ResultItem> mySearchResultItems { get; set; }
}
[Serializable]
public class ResultItem
{
...
}
因此,在我的示例中,我想将 Title 属性映射到 xml 中的
文本值
So, In my example I would like to map Title property to <Head><Title>
text value in xml
感谢您的帮助!!
推荐答案
你不能那样做.您需要为 元素创建另一个类
You can't do that. You need to create another class for the <Head>
element
[XmlRoot(ElementName = "GSP")]
public class SearchResult
{
[XmlElement(ElementName = "Head")]
public Head Head { get; set; }
[XmlArray(ElementName = "Results")]
[XmlArrayItem(ElementName = "Result")]
public List<ResultItem> mySearchResultItems { get; set; }
}
public class Head
{
[XmlElement(ElementName = "Title")]
public string Title { get; set; }
}
public class ResultItem
{
...
}
此外,如果 Title 元素必须有一个属性,您还需要为 Title 元素创建一个新类...
Also, if the Title element must have an attribute, you will also need to create a new class for the Title element...
顺便说一下,[Serializable]
属性与 XML 序列化无关...
By the way, the [Serializable]
attribute has nothing to do with XML serialization...
这篇关于c#将二级元素序列化为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!