2

I want to build the following XML node from a class.

<Foo id="bar">some value</Foo>

How should my class definition be?

class Foo
{
   public string Value {set;get;}
   public string id{set;get;}
}

I believe i should put some XML attributes to these properties but not sure what they are.

2 Answers 2

9

Take a look at the attributes under the System.Xml.Serialization namespace for that. In your case, the class should look like the code below.

public class StackOverflow_8281703
{
    [XmlType(Namespace = "")]
    public class Foo
    {
        [XmlText]
        public string Value { set; get; }
        [XmlAttribute]
        public string id { set; get; }
    }
    public static void Test()
    {
        MemoryStream ms = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(Foo));
        Foo foo = new Foo { id = "bar", Value = "some value" };
        xs.Serialize(ms, foo);
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }
}

Update: added code to serialize the type.

Sign up to request clarification or add additional context in comments.

4 Comments

ok and how can i generate XML from this class after assigning the values?
Edited the answer with example. You'll use the XmlSerializer class for that.
thanks. is this an efficient way to generate XML? is there better/faster ways i should research?
It'll only be inefficient if you overuse it. The serializer is quite performant for most of the scenarios. If it becomes a problem, you can look into other alternatives, but don't try to optimize your code until you need it.
3

For C# and Visual Basic, there is no reason to do this by hand. Visual Studio includes a command line tool that will generate the class or xml schema for you. See http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=VS.100).aspx for details.

4 Comments

Really? Down votes because I recommend using the tool that exists instead of doing it by hand?
I agree - why down vote this? And even more, why down vote with no explanation. That is not helpful or polite. If you are working with a well defined schema (and if you aren't, why not - they are very helpful except in very simple case) then this is a great tool. It let's you update your schema in one place and regenerate the code - much better than manually updating code and schema.
This tool is really great. I also can not understand why downvoting, so i gave you an upvote :)
I also don't understand the downvotes - I've used the tool in the past and although I don't like its output too much (its output tends to be too verbose), it's often a good starting point for handcrafting a simple class for the purpose. Upvoted it as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.