Suppress blank namespace in XML element

I have an XML element I am creating. I want Xmlns information to appear in the parent element but no references in any child elements. To acheive this, I am using the following code:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
XNamespace xns = "http://tv2.microsoft.com/test/jobscheduler";
var xroot = new XElement(xns + "Constraints", new XAttribute(XNamespace.Xmlns + "xsd", xsd.NamespaceName), new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName));
var keyElement = new XElement("Keys");
var kElement = new XElement("K");
kElement.Value = "HDD";
keyElement.Add(kElement);
xroot.Add(keyElement);
xroot.Add(new XElement("Properties"));
xroot.Add(new XElement("MustIncludeKeys"));

What I am getting is:

<Constraints xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tv2.microsoft.com/test/jobscheduler">
  <Keys xmlns="">
    <K>HDD</K>
  </Keys>
  <Properties xmlns="" />
  <MustIncludeKeys xmlns="" />
</Constraints>

What I want is:

<Constraints xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tv2.microsoft.com/test/jobscheduler">
  <Keys>
    <K>HDD</K>
  </Keys>
  <Properties />
  <MustIncludeKeys />
</Constraints>

What can I do to get rid of the extraneous (blank) name spaces "xmlns="" "? I've tried keyElement.ReplaceAttributes("") and even tried using the System.Xml namespace to use the RemoveAttribute Method - to no avail.

Jon Skeet
people
quotationmark

I have an XML element I am creating. I want Xmlns information to appear in the parent element but no references in any child elements

That means you want the child elements to be in the same namespace as the default namespace set by the parent... so you should do that explicitly, as otherwise they'll be in the "empty" namespace (which will then come out as xmlns="" in the XML):

var keyElement = new XElement(xns + "Keys");
...

Note that your whole XML generation can easily be done in a single statement:

var xroot = new XElement(xns + "Constraints",
    new XAttribute(XNamespace.Xmlns + "xsd", xsd.NamespaceName),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
    new XElement(xns + "Keys",
        new XElement(xns + "K", "HDD")
    ),
    new XElement(xns + "Properties"),
    new XElement(xns + "MustIncludeKeys")
);

Basically, you need to know that child elements inherit the default namespace from their parent elements unless they specify a different namespace. Note that this doesn't happen with attributes.

people

See more on this question at Stackoverflow