XML Serialization Of A Class With Attributes

  • Thread starter Thread starter Amy L.
  • Start date Start date
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.
 
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.
 
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
 
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.
 
Back
Top