【问题标题】:Accessing Child nodes during Xml Serialization在 Xml 序列化期间访问子节点
【发布时间】:2010-02-12 20:11:33
【问题描述】:

如何在序列化期间访问 Name 元素的子元素?

<Person>
    <Name>
        <First>John</First>
        <Middle>Adam</Middle>
        <Last>Smith</Last>
        <Madian></Madian>
    </Name>
    <Gender>M</Gender>
</Person>
[XmlRootAttribute("Person", IsNullable= false)]
public class Person
{
    [XmlElement(ElementName = "Name/First")]
    public string firstName;
    [XmlElement(ElementName = "Name/Middle", IsNullable = true)]
    public string middleName;
    [XmlElement(ElementName = "Name/Last")]
    public string lastName;
    [XmlElement(ElementName = "Name/Madian", IsNullable = true)]
    public string madianName;

    [XmlElement(ElementName = "Gender", DataType = "string")]
    public string gender;

    ...

【问题讨论】:

  • 不确定我理解您的意思在序列化期间。围绕实施的过程是什么?

标签: c# xml xml-serialization


【解决方案1】:
    [XmlArray("Person")]
    [XmlArrayItem("Name", typeof(Name))]
    public List<Name> Name{ get; set; }

【讨论】:

  • 从我的角度来看,这确实回答了原始问题。
【解决方案2】:

你需要创建一个中间类:

public class Name
{
    [XmlElement(ElementName = "First")]
    public string firstName;
    [XmlElement(ElementName = "Middle", IsNullable = true)]
    public string middleName;
    [XmlElement(ElementName = "Last")]
    public string lastName;
    [XmlElement(ElementName = "Madian", IsNullable = true)]
    public string madianName;
}

然后在Person里面使用这个类:

[XmlRootAttribute("Person", IsNullable= false)]
public class Person
{
    public Name Name;

    [XmlElement(ElementName = "Gender", DataType = "string")]
    public string gender;

    ...
}

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2011-01-23
    相关资源
    最近更新 更多