views:

5055

answers:

2

We were given a sample document, and need to be able to reproduce the structure of the document exactly for a vendor. However, I'm a little lost with how C# handles namespaces. Here's a sample of the document:

<?xml version="1.0" encoding="UTF-8"?>
<Doc1 xmlns="http://www.sample.com/file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.sample.com/file/long/path.xsd"&gt;
    <header>
        <stuff>data</stuff>
        <morestuff>data</morestuff>
    </header>
 </Doc1>

How I'd usually go about this is to load a blank document, and then start populating it:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<Doc1></Doc1>");
// Add nodes here with insert, etc...

Once I get the document started, how do I get the namespace and schema into the Doc1 element? If I start with the namespace and schema in the Doc1 element by including them in the LoadXml(), then all of the child elements have the namespace on them -- and that's a no-no. The document is rejected.

So in other words, I have to produce it EXACTLY as shown. (And I'd rather not just write text-to-a-file in C# and hope it's valid XML).

+4  A: 

You should try it that way

  XmlDocument doc = new XmlDocument();  

  XmlSchema schema = new XmlSchema();
  schema.Namespaces.Add("xmlns", "http://www.sample.com/file");

  doc.Schemas.Add(schema);

Do not forget to include the following namespaces:

using System.Xml.Schema;
using System.Xml;
Greco
A: 

If you are using Visual Studio 2008 in the Samples folder you'll find a sample addin that let's you paste a XML fragment as Linq2XML code.

Scott Hanselman has a blog post with the details.

I think this is the quickest way to go from a sample XML doc to C# code that creates it.

Pop Catalin
No .Net 3.0+ here yet. Still 2.0.
clintp