Question

I'd like to write the following XML:

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

Based on this example I've created this 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>

I used xsd.exe (VS Command Prompt) to generate the classes:

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

Now I'm able to set the attribute "name". But how can I set the main text value between the field elements e.g. [SET THIS TEXT]

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

Solution

Scrap the xsd.exe and generate your model:

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

and then serialize it:

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top