xsi Suprimir: nil, mas ainda mostram vazio elemento quando a serialização em .Net
-
19-09-2019 - |
Pergunta
Eu tenho um # classe c que tem mais de 20 propriedades de cadeia. Eu defini cerca de um quarto das pessoas para um valor real. Eu gostaria de serializar a classe e obter uma saída de
<EmptyAttribute></EmptyAttribute>
para uma propriedade
public string EmptyAttribute {get;set;}
Eu não quero que a saída seja
<EmptyAttribute xsi:nil="true"></EmptyAttribute>
Eu estou usando a seguinte classe
public class XmlTextWriterFull : XmlTextWriter
{
public XmlTextWriterFull(string filename) : base(filename,Encoding.UTF8) { }
public override void WriteEndElement()
{
base.WriteFullEndElement();
base.WriteRaw(Environment.NewLine);
}
}
para que eu possa obter as marcas completos. Eu só não sei como se livrar do xsi:. Nil
Solução 2
Eu estava realmente capaz de descobrir isso. Eu sei que é um pouco de um truque, em alguns aspectos, mas é assim que eu comecei a trabalhar
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(header.GetType());
XmlTextWriterFull writer = new XmlTextWriterFull(FilePath);
x.Serialize(writer, header);
writer.Flush();
writer.BaseStream.Dispose();
string xml = File.ReadAllText(FilePath);
xml = xml.Replace(" xsi:nil=\"true\"", "");
File.WriteAllText(FilePath, xml);
Espero que isso ajude alguém fora
Outras dicas
A maneira de ter o serialize XmlSerializer
uma propriedade sem adicionar o atributo xsi:nil="true"
é mostrado abaixo:
[XmlRoot("MyClassWithNullableProp", Namespace="urn:myNamespace", IsNullable = false)]
public class MyClassWithNullableProp
{
public MyClassWithNullableProp( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:myNamespace") // Default Namespace
});
}
[XmlElement("Property1", Namespace="urn:myNamespace", IsNullable = false)]
public string Property1
{
get
{
// To make sure that no element is generated, even when the value of the
// property is an empty string, return null.
return string.IsNullOrEmpty(this._property1) ? null : this._property1;
}
set { this._property1 = value; }
}
private string _property1;
// To do the same for value types, you need a "helper property, as demonstrated below.
// First, the regular property.
[XmlIgnore] // The serializer won't serialize this property properly.
public int? MyNullableInt
{
get { return this._myNullableInt; }
set { this._myNullableInt = value; }
}
private int? _myNullableInt;
// And now the helper property that the serializer will use to serialize it.
[XmlElement("MyNullableInt", Namespace="urn:myNamespace", IsNullable = false)]
public string XmlMyNullableInt
{
get
{
return this._myNullableInt.HasValue?
this._myNullableInt.Value.ToString() : null;
}
set { this._myNullableInt = int.Parse(value); } // You should do more error checking...
}
// Now, a string property where you want an empty element to be displayed, but no
// xsi:nil.
[XmlElement("MyEmptyString", Namespace="urn:myNamespace", IsNullable = false)]
public string MyEmptyString
{
get
{
return string.IsNullOrEmpty(this._myEmptyString)?
string.Empty : this._myEmptyString;
}
set { this._myEmptyString = value; }
}
private string _myEmptyString;
// Now, a value type property for which you want an empty tag, and not, say, 0, or
// whatever default value the framework gives the type.
[XmlIgnore]
public float? MyEmptyNullableFloat
{
get { return this._myEmptyNullableFloat; }
set { this._myEmptyNullableFloat = value; }
}
private float? _myEmptyNullableFloat;
// The helper property for serialization.
public string XmlMyEmptyNullableFloat
{
get
{
return this._myEmptyNullableFloat.HasValue ?
this._myEmptyNullableFloat.Value.ToString() : string.Empty;
}
set
{
if (!string.IsNullOrEmpty(value))
this._myEmptyNullableFloat = float.Parse(value);
}
}
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
}
Agora, instanciar esta classe e serializá-lo.
// I just wanted to show explicitly setting all the properties to null...
MyClassWithNullableProp myClass = new MyClassWithNullableProp( ) {
Property1 = null,
MyNullableInt = null,
MyEmptyString = null,
MyEmptyNullableFloat = null
};
// Serialize it.
// You'll need to setup some backing store for the text writer below...
// a file, memory stream, something...
XmlTextWriter writer = XmlTextWriter(...) // Instantiate a text writer.
XmlSerializer xs = new XmlSerializer(typeof(MyClassWithNullableProp),
new XmlRootAttribute("MyClassWithNullableProp") {
Namespace="urn:myNamespace",
IsNullable = false
}
);
xs.Serialize(writer, myClass, myClass.Namespaces);
Depois de recuperar o conteúdo do XmlTextWriter
, você deve ter o seguinte resultado:
<MyClassWithNullableProp>
<MyEmptyString />
<MyEmptyNullableFloat />
</MyClassWithNullableProp>
Espero que isso demonstra claramente como o XmlSerializer
built-in .NET Framework pode ser usado para propriedades serialize para um elemento vazio, mesmo quando o valor da propriedade é nula (ou algum outro valor que você não quer serialize). Além disso, eu mostrei como você pode certificar-se de que as propriedades null
não são serializados em tudo. Uma coisa a nota, se você aplicar um XmlElementAttribute
e defina a propriedade IsNullable
desse atributo para true
, em seguida, que a propriedade serializará com o atributo xsi:nil
quando a propriedade é null
(a não ser em algum lugar anulado mais).