views:

41

answers:

3

Hi Im trying to create a xml the should look like this

<?xml version="1.0" encoding="iso-8859-1"?>
<MyTestSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Tests>
    <Test>
      <messaure>1</messaure>
      <height>4</height>
    </Test>
    <Test>
      <messaure>4</messaure>
      <height>53</height>
    </Test>
  </Tests>
</MyTestSet>

Its not a problem to create the Tests or Test elements, but what is the best way to Create the "MyTestSet" including the namespaces? Im using c# XMLDocument

+1  A: 

This works for me:

XmlDocument.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
XmlDocument.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");

If you want to create the entire document you've posted, you might not want to forget the XML declaration:

        XmlDeclaration xml_declaration;
        xml_declaration = XmlDocument.CreateXmlDeclaration("1.0", "ISO-8859-1", "yes");

        XmlElement document_element = XmlDocument.DocumentElement;
        XmlDocument.InsertBefore(xml_declaration, document_element);

In certain cases you might need it.

Rob
+1  A: 

This question also shows another way of doing this: http://stackoverflow.com/questions/443250/creating-a-specific-xml-document-using-namespaces-in-c

You could alternatively use the XmlNamespaceManager class

http://msdn.microsoft.com/en-us/library/d6730bwt%28VS.80%29.aspx

Finally there is always Linq too, you could use a XDocument and XNamespace

http://msdn.microsoft.com/en-us/library/bb387075.aspx

Aim Kai
+1  A: 

You don't need the xsd and xsi namespaces since you don't use them. Any piece of code that requires them to be there is badly broken and should either be fixed, or else publicly ridiculed.

John Saunders