Search code examples
c#xmlcreation

XML blank attribute creation, issue with ':' character


I am trying to create an xml with the following code.

XmlDocument xmlDocument = new XmlDocument();

XmlProcessingInstruction xPI = xmlDocument.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlDocument.AppendChild(xPI);

XmlElement xElmntheader = xmlDocument.CreateElement("soapenv:Header", " ");
xmlDocument.AppendChild(xElmntheader);

MemoryStream ms = new MemoryStream();
xmlDocument.Save(ms);

string text = System.Text.Encoding.GetEncoding("UTF-8").GetString(ms.GetBuffer(), 0, (int)ms.Length);

Output is

<xml version='1.0' encoding='UTF-8'?>
<soapenv:Header xmlns:soapenv=" " />

I was trying to create like this

<xml version='1.0' encoding='UTF-8'?>
<soapenv:Header/>

How do I eliminate xmlns:soapenv=" " from soapenv:Header?

Any help would be greatly appreciated.


Solution

  • What you're asking how to do is create ill-formed (syntactically incorrect) XML. The XmlDocument API is not designed to do that.

    If you use the element name

    soapenv:Header
    

    that means soapenv is a namespace prefix, which has been declared on this element (or an ancestor) using the xmlns:soapenv pseudoattribute. If it has not been declared, your XML output will not be accepted by any self-respecting XML parser.

    The method signature you called,

    xmlDocument.CreateElement(string1, string2);
    

    takes two arguments: the qualified name of the element (which may include a prefix, as it does in your case); and a namespace URI. The documentation shows what the expected output is:

    The following C# code

    XmlElement elem;
    elem = doc.CreateElement("xy:item", "urn:abc");
    

    results in an element that is equivalent to the following XML text.

    <xy:item xmlns:item="urn:abc"/>
    

    The expected namespace URI for this element is "http://schemas.xmlsoap.org/soap/envelope/". So you will want to declare the soapenv prefix with that namespace URI:

    string soapNSURI = "http://schemas.xmlsoap.org/soap/envelope/";
    

    and use it thus:

    XmlElement xElmntheader = xmlDocument.CreateElement("soapenv:Header", soapNSURI);