J4N
J4N

Reputation: 20697

Write XElement with XmlWriter with the XmlWriter namespace?

I have an XmlWriter, which has already a root element with the xmlns property set.

I now have an XElement(with a lot of subelement), with no Namespace specified.

If I just do:

    xElement.WriteTo(writer);

I end with an invalid xml:

<MyRootElement xmlns="SomeNameSpace">
    <!-- Some elements of this namespace -->

    <MyXElementType  xmlns="">
        <!-- A lot of other Element in the same namespace -->
    </MyXelementType>
    <!-- Some elements of this namespace -->
</MyRootElement>

Since it's forbidden to specify an empty namespace. This is problematic since I need to make after an XSD to validate this.

What could I do to end with this:

    <MyXElementType><!-- HERE, no xmlns !!! -->
        <!-- A lot of other Element in the same namespace -->
    </MyXelementType>
    <!-- Some elements of this namespace -->
</MyRootElement>

Upvotes: 1

Views: 449

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

What makes you think it's invalid? The spec says:

The attribute value in a default namespace declaration MAY be empty. This has the same effect, within the scope of the declaration, of there being no default namespace.

If you want to remove it, then you need to set the namespace of your XElement and its descendants to the same namespace as your existing root element before writing it. You can either do this when it's created:

XNamespace ns = "SomeNamespace";
var element = new XElement(ns + "MyXElementType");

Or after the fact:

foreach (var element in element.DescendantsAndSelf())
{
    element.Name = ns + element.Name.LocalName;
}

Upvotes: 1

Related Questions