1

I have to serialize the following object using ServiceStack.Text.XmlSerializer.Serialize removing all the attributes. I know that it's a bad practice but I've to dialog with an old c++ written server via simulated XML (it's parsed manually) and it doesn't handle the attributes and so on

My class is

[DataContract(Namespace = "", Name = "DataValutaRequest")]
public class DateValueRequestPayload
{
    [DataMember()]
  
    public int Cross { get; set; }
    [DataMember()]
 
    public DateTime TradeDate { get; set; }
}

and it got serialized to

<?xml version="1.0" encoding="utf-8"?><DataValutaRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Cross>11</Cross><TradeDate>2015-07-27T00:00:00+02:00</TradeDate></DataValutaRequest>

I need to remove

<?xml version="1.0" encoding="utf-8"?>
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"

How can I do that? Thanks

UPDATE 1: that's not duplicated since it's related to servicestack's serialization and not MS one...

Community
  • 1
  • 1
advapi
  • 3,661
  • 4
  • 38
  • 73

2 Answers2

1

The xmlns:i XML Namespace is automatically emitted by .NET's DataContractSerializer and doesn't provide an option to omit it.

Only real way to remove it is to serialize to XML and then strip the attributes from the raw XML, e.g something like:

var xml = dto.ToXml()
    .Replace(" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"","");
return xml;

If you have more complicated requirements you can also look at loading and removing XML with XDocument.

Community
  • 1
  • 1
mythz
  • 141,670
  • 29
  • 246
  • 390
-1

If you always only need to remove those two text, you can use

serialized = serialized.Remove(0, @"<?xml version=""1.0"" encoding=""utf-8""?>".Length);
serialized = serialized.Remove(test.IndexOf(@"xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"), @"xmlns:i=""http://www.w3.org/2001/XMLSchema-instance".Length);

It is a really simple way of doing this, as it will not actually parse the xml, so if you need a more generic method you have to parse the xml and use that information to remove the parts.

jalgames
  • 781
  • 4
  • 23