Reputation: 123
Below I have the following objects:
[XmlRoot("ExampleObject")]
public class ExampleObject
{
[XmlElement("element1")]
public long element1{ get; set; }
[XmlElement("element2")]
public string element2{ get; set; }
[XmlElement("element3")]
public string element3{ get; set; }
[XmlElement("element4")]
public ExampleObject2 element4{ get; set; }
}
[Serializable()]
public class ExampleObject2
{
[XmlText]
public string Value { get; set; }
[XmlAttribute]
public string Id { get; set; }
[XmlAttribute]
public string Ref { get; set; }
}
and the following XML:
<c:ExampleObject>
<c:element1>
...
</c:element1>
<c:element2>
...
</c:element2>
<c:element3>
...
</c:element3>
<c:element4 z:Ref="953" i:nil="true"/> <!--- or this <c:Status z:Id="953">...</c:element4> -->
</ExampleObject>
I am able to get my object perfectly fine, except for element4
where inside ExampleObject2
my Id
and Ref
are null while Value
has the correct value inside.
I want it so that ExampleObject2
always has a Value
, it is either null or the value it is supposed to has. I want Id
and Ref
to be the value of the attribute inside element4
depending on if element4
has that attribute or not.
I was wondering if there's something I am missing?
I have also tried to add specific names for the XMLElement tags like this [XmlAttribute("Id")]
but that doesn't seem to do anything. I have also tried including the namespace like this [XmlAttribute("z:Id")]
but that causes an error.
I have also tried putting IsNullable
within the element4 XMLElement
tag but for the XML elements that have nil="true"
but it makes the entire ExampleObject2
null which isn't exactly what I am looking for.
I've already looked at the following question and have come to the same issue.
how to deserialize an xml node with a value and an attribute using asp.net serialization
Thank you
Upvotes: 1
Views: 920
Reputation: 123
I ended up fixing it with the Nil property like @GeorgeBirbilis said and used it with @dbc's solution to manually naming the namespaces the z: and c: are from. I was only doing one or the other, not both combined. Thank you guys for the help.
[XmlAttribute(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/")]
public int Id { get; set; }
[XmlAttribute(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/")]
public int Ref { get; set; }
private bool _nil;
[XmlAttribute("nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public bool Nil
{
get
{
return _nil;
}
set
{
_nil = value;
}
}
Upvotes: 1