deathrace
deathrace

Reputation: 1076

removing namespace tag (xmlns:) from XMLSerializer

I want to generate following xml output in my C# code :

<?xml version="1.0" encoding="utf-16"?>
<CallConnectReq Xmlns="urn:interno-com:ns:a9c" reqId="9" msgNb="2">
  <LocalCallId>0</LocalCallId>
</CallConnectReq>

right now I am achieving this as follows:

var xnameSpace = new XmlSerializerNamespaces();
                xnameSpace.Add("Xmlns", Constants.XmlNameSpaceValue);
                var xmlSerializer = new XmlSerializer(objToSerialize.GetType());
                var stringWriter = new StringWriter();
                xmlSerializer.Serialize(stringWriter, objToSerialize, xnameSpace);
                return stringWriter.ToString().**Replace("xmlns:","");**

But I want to remove "xmlns:" tag without using Replace() method. Is there any way to do it?

Upvotes: 2

Views: 10219

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063944

If you genuinely want Xmlns (which, to restate, I strongly believe is a typo of xmlns, and if not: is a bad choice in that it adds confusion), then:

var xnameSpace = new XmlSerializerNamespaces();
xnameSpace.Add("", "");
var ser = new XmlSerializer(typeof (CallConnectRequest));
ser.Serialize(destination, new CallConnectRequest {
    RequestId = 9,
    MessageNumber = 2,
    LocalCallId = 0
}, xnameSpace);

using:

[XmlRoot("CallConnectReq")]
public class CallConnectRequest {
    [XmlAttribute("Xmlns"), Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string XmlNamespace {
        get { return "urn:interno-com:ns:a9c";} set { }
    }
    [XmlAttribute("reqId")]
    public int RequestId { get; set; }
    [XmlAttribute("msbNb")]
    public int MessageNumber { get; set; }

    [XmlElement("LocalCallId")]
    public int LocalCallId { get; set; }
}

which writes:

<?xml version="1.0" encoding="ibm850"?>
<CallConnectReq Xmlns="urn:interno-com:ns:a9c" reqId="9" msbNb="2">
  <LocalCallId>0</LocalCallId>
</CallConnectReq>

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063944

To add just the default namespace:

var xnameSpace = new XmlSerializerNamespaces();
xnameSpace.Add("", "urn:interno-com:ns:a9c");
var ser = new XmlSerializer(typeof (CallConnectRequest));
ser.Serialize(destination, new CallConnectRequest(), xnameSpace);

with:

[XmlRoot("CallConnectReq", Namespace = "urn:interno-com:ns:a9c")]
public class CallConnectRequest {}

Upvotes: 4

Related Questions