How to Add Attributes for C# Xml Serialization

How to add attributes for C# XML Serialization

Where do you have the type stored?

Normally you could have something like:

class Document {
[XmlAttribute("type")]
public string Type { get; set; }
[XmlText]
public string Name { get; set; }
}

public class _Filter
{
[XmlElement("Times")]
public _Times Times;
[XmlElement("Document")]
public Document Document;
}

C# - Add attribute in node when serialization

I would do the following:

Add another property

public class Customer
{
[XmlAttribute]
public int id {get;set;}

public string FirstName { get; set; }
public string LastName { get; set; }
}

In assinging values to the Customer object:

new Customer()
{
id = 1,
FirstName = "FirstName1",
LastName = "LastName1"
},

This would give the output for every customer when an id is assigned as follow

<myclass>
<Customer id=1>
<FirstName>FirstName1</FirstName>
<LastName>LastName1</LastName>
</Customer>
<Customer id=2>
<FirstName>FirstName2</FirstName>
<LastName>LastName2</LastName>
</Customer>
</myclass>

I would assume the Propertie1 in myClass will also have the [XmlAttribute]
making it

<myclass Propertie1 = "<assinged value>">

This post provides a good overview

XmlSerializer add attribute

Yes, you can do this using the XmlAttribute attribute. In order to do this, you need to define your custom attribute. It comes with the price of one more class that represents the array (nested in the root node). If you have no problem with this addition, then the solution can look like this:

public class ArrayOfMovie
{
// define the custom attribute
[XmlAttribute(AttributeName="CustomAttribute")]
public String Custom { get; set; }
// define the collection description
[XmlArray(ElementName="Items")]
public List<Movie> Items { get; set; }
}

public class Movie
{
public string VideoId { get; set; }
public string Title { get; set; }
}

Then create, fill and serialize as you already do - the one new thing is to fill your custom attribute:

// create and fill the list
var tmpList = new List<Movie>();
tmpList.Add(new Movie { VideoId = "1", Title = "Movie 1" });
tmpList.Add(new Movie { VideoId = "2", Title = "Movie 2" });
// create the collection
var movies = new ArrayOfMovie
{
Items = tmpList,
Custom = "yes" // fill the custom attribute
};
// serialize
using (var writer = XmlWriter.Create(serializationFile, settings))
{
var serializer = new XmlSerializer(typeof(ArrayOfMovie));
serializer.Serialize(writer, movies);
}

The XML output looks like this:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
CustomAttribute="yes">
<Items>
<Movie>
<VideoId>1</VideoId>
<Title>Movie 1</Title>
</Movie>
<Movie>
<VideoId>2</VideoId>
<Title>Movie 2</Title>
</Movie>
</Items>
</ArrayOfMovie>

how to add attributes to xml using xml serializer

You can use:

XElement x;
XAttribute attribute = new XAttribute("AttributeName", object);
x.Add(attribute);

Or:

XElement x = new XElement("AutoReportXML",
new XAttribute("ReportName", "somename"),
new XAttribute("ReportID", 34)
/* , add more here */);

How to Serialize to XML containing attributes?

It would be best if you had an XSD file describing the XML you will be receiving from the server. You could then use the XSD.EXE program to produce .NET classes with the appropriate .NET attributes on them. You could then just use XmlSerializer.Deserialize.

I'm going to try to create such a class for you by hand. This will be a quick attempt, and may be wrong (I have to get back to work!)


Try this and see if it works.

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

[XmlRoot("answer")]
public class Answer
{
[XmlElement]
public List<Player> Players { get; set; }
}

public class Player
{
[XmlAttribute("id")]
public int ID { get; set; }

[XmlElement]
public List<Coordinate> Coordinates { get; set; }

[XmlElement("action")]
public PlayerAction Action { get; set; }
}

public class PlayerAction
{
[XmlAttribute("name")]
public string Name { get; set; }

[XmlAnyElement]
public XmlElement[] ActionContents { get; set; }
}

public enum Axis
{
[XmlEnum("x")]
X,
[XmlEnum("y")]
Y,
[XmlEnum("z")]
Z
}

public class Coordinate
{
[XmlAttribute("axis")]
public Axis Axis { get; set; }

[XmlText]
public double Value { get; set; }
}

C# XML Serialization How To Set Attribute xsi:type

Do it the correct way :

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

namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Valué value = new CD() { OtherAttributes = "IDK" };
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME, settings);
XmlSerializer serializer = new XmlSerializer(typeof(Valué));
serializer.Serialize(writer, value);

}
}
[XmlInclude(typeof(CD))]
public class Valué
{
}
public class CD : Valué
{
[XmlAttribute(attributeName: "otherAttributes")]
public string OtherAttributes { get; set; }
}
}

C# Add an XML Attribute Using Object & XMLSerializer

You will have to use a custom type instead of a string.

public class Definition
{
[XmlAttribute("active")]
public bool Active;

[XmlText]
public string Text;
}

then define the Definitions property like so

[XmleElement("string")]
public Definition[] Definitions { get; set; }

Add friendly name attribute to xml element using c# attribute for serialization?

There is not an attribute that will do that. Its not common to mix element documentation with the xml data. Usually, you want to document your xml schema with an xsd document or some other means.

That being said, here is how you could do it. You'd need to change the ISBN property from a string to a custom type that has a friendlyName property that you can serialize.

public class Book
{
public string Title { get; set; }

public ISBN ISBN { get; set; }
}

public class ISBN
{
[XmlText]
public string value { get; set; }

[XmlAttribute]
public string friendlyName { get; set; }
}

The following will serialize exactly like what you have in your question.

Book b = new Book
{
Title = "To Kill a Mockingbird",
ISBN = new ISBN
{
value = "9780061120084",
friendlyName = "International Standard Book Number",
}
};

UPDATE

OK, another approach would be to create a custom XmlWriter that can intercept calls made by the serializer to create elements. When an element is being created for an property that you want to add a friendly name to, you can write in your own custom attribute.

public class MyXmlTextWriter : XmlTextWriter
{
public MyXmlTextWriter(TextWriter w)
: base(w)
{
}

public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement(prefix, localName, ns);

switch(localName)
{
case "ISBN":
WriteAttributeString("friendlyName", "International Standard Book Number");
break;
}
}
}

Here is an example of how you would use it (from a console app):

XmlSerializer serializer = new XmlSerializer(typeof(Book));
serializer.Serialize(new MyXmlTextWriter(Console.Out), b);

You can implement the other constructors of XmlTextWriter, if you need to be able to write to other things like a Stream.



Related Topics



Leave a reply



Submit