6

is there a simple way to remove the namespace from the XML root element. I have tried with

[XmlRootAttribute("MCP", Namespace = "", IsNullable = false)]    

on the serializable class. But no use. still getting the same result.

sample class

[Serializable]
[XmlRootAttribute("MCP", Namespace = "", IsNullable = false)]    
public class BINDRequest
{
    public BINDRequest()
    {

    }
    [XmlAttribute]
    public string CLIENT_REQUEST_ID { get; set; }

    public BINDRequestBody BIND { get; set; }

}

result xml

<?xml version="1.0" encoding="utf-8"?>
<MCP xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" CLIENT_REQUEST_ID="1">
  <BIND CLIENT_ID="test" PASSWORD="test" />
</MCP>

i don't understand then whats the use of specifying namsespace in XmlRootAttribute??

3
  • The need for a namespace is so you can have two classes with the same Name, and differentiate between them. Also if you link in external classes, they could conflict with your own, so you should differentiate. If you link in a Profile object from two sources, they need to be different when you program against them. Commented Sep 13, 2010 at 9:21
  • @Mikael, i understand that... but if i specify namespace as empty, then it should not include it.. right?? Commented Sep 13, 2010 at 9:26
  • and Daring showed you how. I was just stating why a namespace is useful, and imo you should always have one. Commented Sep 13, 2010 at 11:10

1 Answer 1

19

Try this:

public class BINDRequest
{
    [XmlAttribute]
    public string CLIENT_REQUEST_ID { get; set; }
}

class Program
{
    static void Main()
    {
        var request = new BINDRequest
        {
            CLIENT_REQUEST_ID = "123"
        };
        var serializer = new XmlSerializer(request.GetType());
        var xmlnsEmpty = new XmlSerializerNamespaces();
        xmlnsEmpty.Add("", "");
        using (var writer = XmlWriter.Create("result.xml"))
        {
            serializer.Serialize(writer, request, xmlnsEmpty);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.