سؤال

public class MyStuff {
    public string Name { get; set; }

    public List<Annotation> Annotations { get; set; }
}

public class Annotation {
    public string Name { get; set; }
    public string Value { get; set; }
}

How do I get the List of Annotations to serialize as a bunch of XML attributes?

var x = new MyStuff {
    Name = "Stuff",
    Annotations = new [] {
        new Annotation { Name = "Note1", Value = "blah" },
        new Annotation { Name = "Note2", Value = "blahblah" }
    }.ToList()
};

// turns into something like:
<MyStuff Name="Stuff" ann:Note1="blah" ann:Note2="blahblah" />
هل كانت مفيدة؟

المحلول 4

The IXmlSerializable interface allows you to customize the serialization of any class.

public class MyStuff : IXmlSerializable {
    public string Name { get; set; }

    public List<Annotation> Annotations { get; set; }

    public XmlSchema GetSchema() {
        return null;
    }

    public void ReadXml(XmlReader reader) {
        // customized deserialization
        // reader.GetAttribute() or whatever
    }

    public void WriteXml(XmlWriter writer) {
        // customized serialization
        // writer.WriteAttributeString() or whatever
    }

}

نصائح أخرى

ann:Note1 is only valid if ann is an xml namespace,

XNamespace ns = "Annotation";

XElement xElem = new XElement("MyStuff", new XAttribute("Name",x.Name));
xElem.Add(x.Annotations
           .Select(a => new XAttribute(ns + a.Name, a.Value)));

var xml = xElem.ToString();

OUTPUT:

<MyStuff Name="Stuff" p1:Note1="blah" p1:Note2="blahblah" xmlns:p1="Annotation" />
XmlDocument doc = new XmlDocument(); // Creating an xml document
XmlElement root =doc.CreateElement("rootelement"); doc.AppendChild(root); // Creating and appending the root element
XmlElement annotation = doc.CreateElement("Name");
XmlElement value = doc.CreateElement("Value");
annotation.InnerText = "Annotation Name Here";
value.InnerText = "Value Here";
doc.AppendChild(annotation);
doc.AppendChild(value);

You can narrow all your list and do the same thing in a loop.

What you can do is add the attribute [XmlAttribute] on your properties:

public class Annotation
{
    [XmlAttribute]
    public string Name { get; set; }

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

And the result will be like this:

<Annotations>
  <Annotation Name="Note1" Value="blah" /> 
  <Annotation Name="Note2" Value="blahblah" /> 
</Annotations>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top