none
Serialize without xmlns RRS feed

  • Question

  • Hi,

    I'm trying to serialize a object without namespaces. I tried this:

    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    XmlSerializer slz = new XmlSerializer(someType);
    slz.Serialize(myXmlTextWriter, someObject, ns);

    But it does not work? i get all my elements with namespaces:

    <ID xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">2190583</ID>
    <IssueDate xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">2019-11-15</IssueDate>

    How to prevent that?

    Tuesday, December 3, 2019 3:12 PM

All replies

  • Hi KBid,

    Here is method to remove all namespaces in c#. You can use it as a next step after the serialization.

    c#:

    void Main()
    {
    	XElement docX = XElement.Parse(@"<NameAddressResponse xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    				                     xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
    					<TransactionFor xmlns='something'>VSAM-SQL</TransactionFor>
    					<StatusCode a='b'>0</StatusCode>
    					<Message>Request successfully completed</Message>
    				</NameAddressResponse>");
    
    	stripNS(docX);
    	docX.Dump("After");
    }
    
    // Define other methods and classes here
    static XElement stripNS(XElement Xml)
    {
    	foreach (XElement XE in Xml.DescendantsAndSelf())
    	{
    		// Stripping the namespace by setting the name of the element to it's localname only
    		XE.Name = XE.Name.LocalName;
    		// replacing all attributes with attributes that are not namespaces and their names are set to only the localname
    		XE.ReplaceAttributes((from xattrib in XE.Attributes().Where(xa => !xa.IsNamespaceDeclaration) select new XAttribute(xattrib.Name.LocalName, xattrib.Value)));
    	}
    	
    	return Xml;
    }



    Tuesday, December 3, 2019 3:30 PM