我有一个来自xsd的生成的c#类。当我想给元素赋值时
result res = new result();
res.feed = "123132";
//这有效
res.data在这里我找不到id和值,我该怎么做res.data.id="something"
我有一个xml:
<result>
<feed></feed>
<status></status>
<data>
<id></id>
<value></value>
<id></id>
<value></value>
</data>
</result>
生成此xsd:
<xs:element name="result">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:string" name="feed"/>
<xs:element type="xs:string" name="status"/>
<xs:element name="data">
<xs:complexType>
<xs:choice maxOccurs="unbounded" minOccurs="0">
<xs:element type="xs:string" name="id"/>
<xs:element type="xs:string" name="value"/>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
并使用xsd.exe我为它生成了类
public partial class result {
private string feedField;
private string statusField;
private resultData dataField;
/// <remarks/>
public string feed {
get {
return this.feedField;
}
set {
this.feedField = value;
}
}
/// <remarks/>
public string status {
get {
return this.statusField;
}
set {
this.statusField = value;
}
}
/// <remarks/>
public resultData data {
get {
return this.dataField;
}
set {
this.dataField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class resultData {
private string[] itemsField;
private ItemsChoiceType[] itemsElementNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("id", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("value", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public string[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName {
get {
return this.itemsElementNameField;
}
set {
this.itemsElementNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]
public enum ItemsChoiceType {
/// <remarks/>
id,
/// <remarks/>
value,
}
答案 0 :(得分:2)
看起来您必须执行以下操作
res.data = new resultData();
res.data.ItemsElementName = new []
{
ItemsChoiceType.id,
ItemsChoiceType.value,
ItemsChoiceType.id,
ItemsChoiceType.value,
};
res.data.Items = new []
{
"id 1",
"value 1",
"id 2",
"value 2",
};
基本上,您必须将每个数组设置为包含类型和相应的值。创建数组时,它们应具有相同的长度,类型和值应位于相同的位置。
但是,如果你想要id-value对,你应该重新考虑XML的结构,因为它目前只允许你输入id或只是值,并且不保证顺序或者每个都有相同的数量。也许像下面这样的东西更像是你想要的东西。
<result>
<feed></feed>
<status></status>
<data>
<dataItem>
<id></id>
<value></value>
</dataItem>
<dataItem>
<id></id>
<value></value>
</dataItem>
</data>
</result>