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?
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.
[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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With