Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default XML namespace for an XDocument

Tags:

c#

How can I set the default namespace of an existing XDocument (so I can deserialize it with DataContractSerializer). I tried the following:

var doc = XDocument.Parse("<widget/>"); var attrib = new XAttribute("xmlns",                             "http://schemas.datacontract.org/2004/07/Widgets"); doc.Root.Add(attrib); 

The exception I get is is The prefix '' cannot be redefined from '' to 'http://schemas.datacontract.org/2004/07/Widgets' within the same start element tag.

Any ideas?

like image 758
Anthony Faull Avatar asked May 20 '10 14:05

Anthony Faull


People also ask

How do I change the default namespace in XML?

You can change the default namespace within a particular element by adding an xmlns attribute to the element. Example 4-4 is an XML document that initially sets the default namespace to http://www.w3.org/1999/xhtml for all the XHTML elements.

What is an XML namespace A set of names?

[Definition:] An XML namespace is a collection of names, identified by a URI reference [RFC2396], which are used in XML documents as element types and attribute names.

What is XML namespace in C#?

Represents a collection of nodes that can be accessed by name or index. Resolves, adds, and removes namespaces to a collection and provides scope management for these namespaces. Table of atomized string objects. Represents a single node in the XML document.

How do you add a namespace to an XML element in Java?

Add name space to document root element as attribute. Transform the document to XML string. The purpose of this step is to make the child element in the XML string inherit parent element namespace. Now the xml string have name space.


1 Answers

Not sure if this already worked in .net 3.5 or only in 4, but this works fine for me:

XNamespace ns = @"http://mynamespace"; var result = new XDocument(     new XElement(ns + "rootNode",         new XElement(ns + "child",             new XText("Hello World!")          )      )  ); 

produces this document:

<rootNode xmlns="http://mynamespace">     <child>Hello World!</child> </rootNode> 

Important is to always use the ns + "NodeName" syntax.

like image 76
Michael Stum Avatar answered Sep 25 '22 23:09

Michael Stum