Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a namespace when creating an XML file?

Tags:

c#

xml

I have to create an XML document in C#.

The root element has to look like this:

<valuation-request 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:noNamespaceSchemaLocation="valuations.xsd">

I'm using the following

XmlElement root = X.CreateElement("valuation-request");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.SetAttribute("xsi:noNamespaceSchemaLocation", "valuations.xsd");

However this produces

<valuation-request 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     noNamespaceSchemaLocation="valuations.xsd"> //missing the xsi:

What am I missing?

like image 674
Steven Avatar asked Feb 08 '11 11:02

Steven


People also ask

How do you declare a namespace in XML?

An XML namespace is declared using the reserved XML attribute xmlns or xmlns:prefix , the value of which must be a valid namespace name. Any element or attribute whose name starts with the prefix "xhtml:" is considered to be in the XHTML namespace, if it or an ancestor has the above namespace declaration.

How do I add namespace prefix to XML element?

Adding a namespace prefix to an elementThe XQuery expression in the following SELECT statement adds a namespace prefix to an element. The XQuery expression uses fn:QName to create a QName with a namespace binding. The XQuery let clause creates an empty element with name emp and namespace http://example.com/new .

What is namespace used in XML document?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.

Which keyword is used to declare a namespace in XML?

The xmlns attribute is an XML keyword for a namespace declaration.


1 Answers

Use the overload of SetAttribute, that takes namespace as well:

root.SetAttribute("noNamespaceSchemaLocation", 
    "http://www.w3.org/2001/XMLSchema-instance", 
    "valuations.xsd"
); 
like image 94
Mubashir Khan Avatar answered Oct 19 '22 20:10

Mubashir Khan