14

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">
    <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).

Clinton Pierce
  • 12,859
  • 15
  • 62
  • 90

4 Answers4

29

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;
Dimi Takis
  • 4,924
  • 3
  • 29
  • 41
5

I personally prefer to use the common XmlElement and its attributes for declaring namespaces. I know there are better ways, but this one never fails.

Try something like this:

xRootElement.SetAttribute("xmlns:xsi", "http://example.com/xmlns1");
mathifonseca
  • 1,465
  • 1
  • 15
  • 17
0

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
  • 61,751
  • 23
  • 87
  • 115
0

I found XDocument API far more usable then the older XmlDocument

        XNamespace g = "http://base.google.com/ns/1.0";
        var doc = XDocument.Parse(templateFeed);
        var channel = doc.Descendants("rss").First();

        channel.Add(new XElement("item",
                    new XElement("description", "DDD23"),
                    new XElement(g + "image_link", "http://qqq2")
                 ));

        doc.Save("plik");
vSzemkel
  • 624
  • 5
  • 11