Usman Masood
Usman Masood

Reputation: 1967

adding/creating namespace to root xelement element in c#

i am creating xml using linq.xml through xelement. my hirerachy is some thing like this

I want this schema 2 str

here is my code for schema generation

 XNamespace ns = XNamespace.Get("urn:APISchema.xsd");
 root = new XElement(ns + "Foo");
 root.Add(new XElement("version", "2"));
 root.Add(new XElement("foochild", "str"));

but the resultant schema is

<Foo xlmns="urn:APISchema.xsd">
<version xlmns="">2</version>
<foochild xlmns="">str</foochild>
</Foo>

any idea why such problem why it is appending xlmn to root childs...?

Upvotes: 2

Views: 8958

Answers (4)

Richard Morgan
Richard Morgan

Reputation: 7681

root.Add(new XElement(namespace + "foo", "str"))

Edit: upon further SO searching, this question seems to be addressing the same issue.

Upvotes: 3

Alexander Kahoun
Alexander Kahoun

Reputation: 2488

XNamespace myNamespace = XNamespace.Get("urn:APISchema.xsd");
root = new XElement(myNamespace + "Foo",
    new XElement(myNamespace + "version", "2"),
    new XElement(myNamespace + "foochild", "str"));

Give that a shot, it should do the trick for you.

Upvotes: 0

David Yancey
David Yancey

Reputation: 2030

XNamespace myNameSpace = XNamespace.Get("urn:APISchema.xsd");
        root = new XElement(myNameSpace + "Foo",
                                new XElement(myNameSpace + "foo", "str"));

IMO This is easier to read. But as Richard stated you just need to add the namespace.

Upvotes: 0

Remus Rusanu
Remus Rusanu

Reputation: 294277

You added to the element 'usr:APISchema.xsd::Foo' two elements w/o a namespace. The resulted XML is the expected one. You must add the namespace to each added element: root.Add(new XElement(namespace + "foochild").

Upvotes: 0

Related Questions