I'd like to generate some XML like the following with C# code.
<card>
<name>Cool Card</name>
<set rarity="common">S1</set>
</card>
I have something like this.
public class card
{
public string name = "Cool Card";
[XmlAttribute]
public string rarity = "common";
public string set = "S1";
}
public static void WriteXml()
{
var serializer = new XmlSerializer(typeof(card));
var myCard = new();
using var sw = new StringWriter();
serializer.Serialize(sw, myCard);
XDocument doc = XDocument.Parse(sw.ToString());
XmlWriterSettings xws = new();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
using var xw = XmlWriter.Create(path, xws);
doc.Save(xw);
}
The problem is that this doesn't add the "rarity" attribute to the "set" value. Trying to add [XmlAttribute] adds it to the parent element rather than the next sibling element and I can't figure out how to get it on a plain string element, so at present my output looks like.
<card rarity="common">
<name>Cool Card</name>
<set>S1</set>
</card>
The XML example doc shows an example of how to set the attribute on an element, but only one with nested fields and not one that's a plain string. Is it possible to add an attribute to a plain old string element in XML like my first posted example demonstrates?
