c#将第二级元素序列化为属性

时间:2009-10-08 10:29:03

标签: c# xml-serialization

我正在尝试创建可序列化的类,但我想将第二级元素映射到我的class属性。这样做的最佳方式是什么。

示例xml&类

<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中的<Head><Title>文本值

感谢您的帮助!!

2 个答案:

答案 0 :(得分:4)

你做不到。您需要为<Head>元素

创建另一个类
[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元素创建一个新类...

顺便说一句,[Serializable]属性与XML序列化无关......

答案 1 :(得分:-1)

您不需要自定义序列化。托马斯·莱维斯克是正确的,但你可以使用你用于结果的相同设计方法得到你想要的东西。

示例:

    [XmlRoot(ElementName = "GSP")]
    public class SearchResult
    {
        //public string Title { get; set; }
        [XmlArray(ElementName = "Header")]
        [XmlArrayItem(ElementName = "Title")]
        public List<String> myHeaderItems { get; set; }

        [XmlArray(ElementName = "Results")]
        [XmlArrayItem(ElementName = "Result")]
        public List<ResultItem> mySearchResultItems { get; set; }

        public SearchResult()
        {
            myHeaderItems = new List<String>();
            mySearchResultItems= new List<ResultItem>();
        }

        public SearchResult(string title) : this()
        {
            myHeaderItems.Add(title);
        }
    }

    public class ResultItem
    {
        [XmlText]
        public String Flavor;
    }


    public void Run()
    {
        SearchResult sr = new SearchResult("Search1");
        sr.mySearchResultItems.Add(new ResultItem() {Flavor = "one" }) ; 
        sr.mySearchResultItems.Add(new ResultItem() {Flavor = "two" }) ; 

        var s1 = new XmlSerializer(typeof(SearchResult));

        Console.WriteLine("Serialized:\n{0}", s1.SerializeToString(sr));
    }

生成此输出:

<GSP>
  <Header>
    <Title>Search1</Title>
  </Header>
  <Results>
    <Result>one</Result>
    <Result>two</Result>
  </Results>
</GSP>