XML Serialization Of A Class With Attributes

A

Amy L.

I am trying to serialize a class to xml and I havent been able to figure out
how to add attributes. I am trying to get a node to look like this

<alert type="pager" >True</alert>

I have this so far which produces this
<alert>True</alert>

[XmlElement("alert")]
public string Alert
{
get { return this.alert ; }
set { this.alert = value ; }
}

How would I embed an XML Attribute into that?

Thanks
Amy.
 
A

Amy L.

Oliver,

Yes I did, but it does not add it to the node "alert" instead it adds it to
the root.

Amy.


Oliver Drobnik said:
sorry, I meant: have you tried [XmlAttribute("alert"]?

Amy L. said:
I am trying to serialize a class to xml and I havent been able to figure out
how to add attributes. I am trying to get a node to look like this

<alert type="pager" >True</alert>

I have this so far which produces this
<alert>True</alert>

[XmlElement("alert")]
public string Alert
{
get { return this.alert ; }
set { this.alert = value ; }
}

How would I embed an XML Attribute into that?

Thanks
Amy.
 
D

Dino Chiesa [Microsoft]

using System.Xml.Serialization;

public class Alert {

[XmlAttribute("Type")] // a named attribute
public string Type;
[XmlTextAttribute()] // the text attribute
public bool Status;

static void Main(string[] args) {
Alert a1 = new Alert();
a1.Type= "pager";
a1.Status= true;

XmlSerializer s = new XmlSerializer(typeof(Alert));

// use this to "suppress" the default xsd and xsd-instance namespaces
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );

// Serialize to stdout
s.Serialize(System.Console.Out,a1, ns);
}
}


-Dino
Microsoft

ps:
no need to cross post.
actually there is a more appropriate newsgroup:
microsoft.public.dotnet.xml
 
D

Dino Chiesa [Microsoft]

also! I forgot to mention, xsd.exe is a great tool for helping here.

1. create an xml file of the shape you think you want, eg
<root> <Alert type="pager">True</Alert></root>

2. run xsd.exe on that xml file, generate an xsd

3. run xsd.exe /c on that xsd file, generate a .cs file

4. view and modify the .cs file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top