0

我想编写以下 XML:

<Fields>
    <Field name="john">lorem</Field>
    <Field name="john">lorem</Field>
    <Field name="john">lorem</Field>
</Fields>

基于这个例子,我创建了这个 XSD:

<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="Fields" type="FieldsType" />
  <xsd:complexType name="FieldsType">
    <xsd:sequence>
      <xsd:element maxOccurs="unbounded" name="Field" type="FieldType" />
    </xsd:sequence>
  </xsd:complexType>
  <xsd:complexType name="FieldType">
    <xsd:attribute name="name" type="xsd:string" />
  </xsd:complexType> 
</xsd:schema>

我使用 xsd.exe(VS 命令提示符)来生成类:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute("Fields", Namespace="", IsNullable=false)]
public partial class FieldsType {

    private FieldType[] fieldField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Field")]
    public FieldType[] Field {
        get {
            return this.fieldField;
        }
        set {
            this.fieldField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class FieldType {

    private string nameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

现在我可以设置属性“名称”。但是如何设置字段元素之间的主要文本值,例如 [SET THIS TEXT]

var example = new FieldType();
example.name = "attribute value";
//how to set the element value?
4

1 回答 1

2

报废xsd.exe并生成您的模型:

[XmlRoot("Fields")]
public class MyViewModel
{
    [XmlElement("Field")]
    public Field[] Fields { get; set; }
}

public class Field
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlText]
    public string Value { get; set; }
}

然后序列化它:

var model = new MyViewModel
{
    Fields = new[]
    {
        new Field { Name = "john", Value = "lorem" },
        new Field { Name = "smith", Value = "ipsum" },
    }
};
var serializer = new XmlSerializer(typeof(MyViewModel));
serializer.Serialize(Console.Out, model);
于 2013-01-31T11:50:57.550 回答