如何将名称/值对序列化为属性

时间:2014-04-09 16:37:31

标签: c# xml-serialization

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; }
}

如何将注释列表序列化为一堆XML属性?

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 个答案:

答案 0 :(得分:1)

ann:Note1仅在ann是xml命名空间

时才有效
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();

输出:

<MyStuff Name="Stuff" p1:Note1="blah" p1:Note2="blahblah" xmlns:p1="Annotation" />

答案 1 :(得分:0)

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);

您可以缩小所有列表并在循环中执行相同的操作。

答案 2 :(得分:0)

您可以在属性上添加属性[XmlAttribute]

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

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

结果将是这样的:

<Annotations>
  <Annotation Name="Note1" Value="blah" /> 
  <Annotation Name="Note2" Value="blahblah" /> 
</Annotations>

答案 3 :(得分:0)

IXmlSerializable界面允许您自定义任何类的序列化。

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
    }

}