Shawn
Shawn

Reputation: 228

Adding xmlns namespaces

I really nead to ask you this one, many of you might think it's a simple problem but please help I worked for hours on this one and I am not a step closer to the solution. I really need this one for collage.

I have to create an xml document and this one is working fine.

Now I need to define namespaces or at least I think that is what they are.

I need to insert this into my document

  <language>
    <language id="1" tag="english"/>
    <language id="2" tag="english"/> 
  </language>

And use it like this:

<item id="1">
  <item>
    <item language="1">Periods</item>
  </item>
<item/>

My code:

XmlElement element = xmldoc.CreateElement("", "item", "1");

The problem is that insted of language I get xmlns, where can I define the namespace and how do I create <language id="1" tag="english"/> ?

my problem is that i don't know how to define <language id="1" tag="english"/> and i don't know how can i use it like this <item language="1">Periods</item>

Upvotes: 0

Views: 165

Answers (1)

Mare Infinitus
Mare Infinitus

Reputation: 8162

You could probably write a simple class, for example I use a Speech class like this one:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace StackOverflowSamples
{
    [Serializable]
    public class Speech
    {
        public Speech()
        {
            this.Items = new List<LanguageItem>();
        }

        [XmlArray]
        public List<LanguageItem> Items;
    }

    [Serializable]
    public class LanguageItem
    {
        [XmlAttribute]
        public string Language { get; set; }

        [XmlAttribute]
        public int Id { get; set; }
    }
}

Which can be simply serialized with this code:

// use built in serialization mechanism
XmlSerializer mySerializer = new XmlSerializer(typeof(Speech));
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter("test.xml");

var speech = new Speech();
var lang1 = new LanguageItem() { Id = 1, Language = "English", };
var lang2 = new LanguageItem() { Id = 2, Language = "Slovenian", };
speech.Items.Add(lang1);
speech.Items.Add(lang2);

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");

mySerializer.Serialize(writer, speech, ns);
writer.Close();

Resulting in XML like this here:

<?xml version="1.0" encoding="utf-8"?>
<Speech>
  <Items>
    <LanguageItem Language="English" Id="1" />
    <LanguageItem Language="Slovenian" Id="2" />
  </Items>
</Speech>

Upvotes: 1

Related Questions