Reputation: 303
I want to serialize List of tuples to XML Attributes. For example:
List<Tuple<String, String>> attributes = new List<Tuple<String, String>>();
attributes.Add(New Tuple("att1", value1"));
attributes.Add(New Tuple("att2", value2"));
It should appear as:
<Root att1="value1" att2="value2">
</Root>
Edit: I have a class like this which I am serializing using XmlSerializer:
public class Root
{
List<Tuple<String, String>> attributes = new List<Tuple<String, String>>();
//other attributes and elements exist in this class
}
Is there an easy way of doing it?
Thanks
Upvotes: 0
Views: 3906
Reputation: 21245
Your syntax is incorrect since New
is capitalized in VB not C#.
Please read the documentation for XDocument
and try to work through the examples.
Here is an example:
var attributes = new List<Tuple<string, string>>();
attributes.Add(Tuple.Create("att1", "value1"));
attributes.Add(Tuple.Create("att2", "value2"));
var document = new XDocument();
var root = new XElement("Root");
document.Add(root);
foreach(var node in attributes.Select(x => new XAttribute(x.Item1, x.Item2)))
{
root.Add(node);
}
Console.WriteLine(document); // <Root att1="value1" att2="value2" />
Edit:
To use the XmlSerializer
use attributes:
[XmlType("Root")]
public class Root
{
[XmlAttribute("attr1")]
public string Attribute1 { get; set; }
[XmlAttribute("attr2")]
public string Attribute2 { get; set; }
}
Or you'll need to implement IXmlSerializable
for the dynamic attributes.
Upvotes: 2