我想使用序列化创建一些这样的XML:
<?xml version="1.0" encoding="utf-8"?>
<Person>
<Name>Bob</Name>
<Sex>Male</Sex>
<links rel="relations">
<link rel="self" href="/Persons/Bob" />
<link rel="child" href="/Persons/Lisa" />
</links>
<Person>
现在我知道我可以使用以下方式设置link
项目的属性:
Public Class link
<System.Xml.Serialization.XmlAttribute("rel")>
Public rel As String = ""
<System.Xml.Serialization.XmlAttribute("href")>
Public href As String = ""
End Class
但我无法确定如何在rel
元素上设置links
属性。这将是Person
类设置links
元素的代码:
Public Class Person
...
<System.Xml.Serialization.XmlArray("links")>
Public links As New List(Of link)
End Class
我能以正确的方式解决这个问题吗?
答案 0 :(得分:0)
自定义序列化是一个选项,只需在Person的类上实现IXmlSerializable接口,然后在IXmlSerializable.WriteXml()方法中控制自己如何编写xml。
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
[Serializable]
public class Person : IXmlSerializable
{
public Person()
{
}
public string Name { get; set; }
public string Sex { get; set; }
public Link[] Links {get; set;}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Name", this.Name);
writer.WriteElementString("Sex", this.Sex);
writer.WriteStartElement("links");
writer.WriteAttributeString("rel", "relations");
foreach(Link link in this.Links)
{
writer.WriteStartElement("link");
writer.WriteAttributeString("rel", link.rel);
writer.WriteAttributeString("href", link.href);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
这是调用者代码,它将创建一个Person类,然后在你想要的xml中序列化它
public SerializePerson()
{
Link link1 = new Link() { rel = "self", href = "/Persons/Bob" };
Link link2 = new Link() { rel = "child", href = "/Persons/Lisa" };
Person person = new Person() { Name = "Bob", Sex = "Male"};
person.Links = new Link[] { link1, link2 };
XmlSerializer serializer = new XmlSerializer(typeof(Person));
StreamWriter streamWriter = new StreamWriter(@"C:\temp\serializedBob.txt");
serializer.Serialize(streamWriter, person);
streamWriter.Close();
}