Represent XML without xsd
-
25-09-2019 - |
Question
Note: I cannot use XSD... not going to go into why.
I'm having a problem properly representing the following xml in a class that it should get deserialized into:
XML:
<product>
<sku>oursku</sku>
<attribute name="attrib1">value1</attribute>
<attribute name="attrib2">value2</attribute>
<attribute name="attribx">valuex</attribute>
</product>
the problem is representing the attribute nodes
What I have so far is:
[XmlElement(ElementName = "Attribute")]
public Attribute[] productAttributes;
public class Attribute
{
[XmlAttribute(AttributeName = "Name")]
public string attributeName;
public Attribute()
{
}
}
I know I'm missing something to store the value, and perhaps
Solution
Running xsd.exe
twice on your XML to create an intermediary XSD and then a C# class from it yields this result:
[Serializable]
[XmlType(AnonymousType=true)]
[XmlRoot(Namespace="", IsNullable=false)]
public partial class product
{
private string skuField;
private productAttribute[] attributeField;
[XmlElement(Form=XmlSchemaForm.Unqualified)]
public string sku {
get {
return this.skuField;
}
set {
this.skuField = value;
}
}
[XmlElement("attribute", Form=XmlSchemaForm.Unqualified, IsNullable=true)]
public productAttribute[] attribute {
get {
return this.attributeField;
}
set {
this.attributeField = value;
}
}
}
[Serializable]
[XmlType(AnonymousType=true)]
public partial class productAttribute {
private string nameField;
private string valueField;
[XmlAttribute]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
[XmlText]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
Does that work for you??
OTHER TIPS
The XML you're trying to produce doesn't look like the sort that XmlSerializer is capable of creating natively. I think you're going to have to implement IXmlSerializable and custom-write it.
I think you need to use the attribute [XmlText]
:
public class Attribute
{
[XmlAttribute(AttributeName = "Name")]
public string attributeName;
[XmlText]
public string Value {get;set;}
public Attribute()
{
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow