Search code examples
c#xmllinqxml-namespacesxelement

How to add a namespace when parsing string to Xelement?


I'm looking to set a namespace to the Xelement below. How to achieve it?

string Namespace = "http://mynamespace";
string defaultXml = "<ReferResult><Text> Testing Referred</Text></ReferResult>"

Xelement myXml = XElement.Parse(defaultXml);

// How to add the name space to myXml?

Solution

  • XNamespace Namespace = "http://mynamespace";
    string defaultXml = "<ReferResult><Text> Testing Referred</Text></ReferResult>";
    
    XElement myXml = XElement.Parse(defaultXml);
    myXml.Name = Namespace + myXml.Name.LocalName;
    
    //If you want the children to have the same namespace, use the following.
    //If you want only the parent to have the namespace, omit the code bellow 
    foreach(var element in myXml.Descendants()){
        element.Name = Namespace + element.Name.LocalName;
    }
    
    //Output:
    //<ReferResult xmlns="http://mynamespace">
    //    <Text> Testing Referred</Text>
    //</ReferResult>
    

    Edit: As OP's requested in the comments, to remove the namespaces, just use the same code, but omiting the namespace part:

    myXml.Name = myXml.Name.LocalName;
    foreach(var element in myXml.Descendants()){
        element.Name = element.Name.LocalName;
    }