Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove namespace from XML root element?

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??

like image 718
RameshVel Avatar asked Sep 13 '10 09:09

RameshVel


People also ask

How do I remove namespace prefix?

Once a namespace prefix is created, it cannot be changed or deleted. The workaround is to move all your code to a new Developer Organization, where you can setup the desired Namespace Prefix.

How do I change the default namespace in XML?

You can change the default namespace within a particular element by adding an xmlns attribute to the element. Example 4-4 is an XML document that initially sets the default namespace to http://www.w3.org/1999/xhtml for all the XHTML elements. This namespace declaration applies within most of the document.

Is namespace required in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element.

What is Namespace in XML file?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.


1 Answers

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);
        }
    }
}
like image 116
Darin Dimitrov Avatar answered Nov 14 '22 12:11

Darin Dimitrov