[英]How to Serialize to XML containing attributes?
我有以下代码:
...
request data = new request();
data.username = formNick;
xml = data.Serialize();
...
[System.Serializable]
public class request
{
public string username;
public string password;
static XmlSerializer serializer = new XmlSerializer(typeof(request));
public string Serialize()
{
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Encoding = Encoding.UTF8;
serializer.Serialize(
System.Xml.XmlWriter.Create(builder, settings ),
this);
return builder.ToString();
}
public static request Deserialize(string serializedData)
{
return serializer.Deserialize(new StringReader(serializedData)) as request;
}
}
我想将属性添加到某些节点并创建一些子节点。 还有如何像这样解析xml:
<answer>
<player id="2">
<coordinate axis="x"></coordinate>
<coordinate axis="y"></coordinate>
<coordinate axis="z"></coordinate>
<action name="nothing"></action>
</player>
<player id="3">
<coordinate axis="x"></coordinate>
<coordinate axis="y"></coordinate>
<coordinate axis="z"></coordinate>
<action name="boom">
<1>1</1>
<2>2</2>
</action>
</player>
</answer>
它不是XML文件,而是HTTP服务器的答复。
最好是有一个XSD文件来描述您将从服务器接收的XML。 然后,您可以使用XSD.EXE程序来生成具有相应.NET属性的.NET类。 然后,您可以只使用XmlSerializer.Deserialize
。
我将尝试为您手动创建此类。 这将是一次快速尝试,并且可能是错误的(我必须重新开始工作!)
试试这个,看看是否可行。
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot("answer")]
public class Answer
{
[XmlElement]
public List<Player> Players { get; set; }
}
public class Player
{
[XmlAttribute("id")]
public int ID { get; set; }
[XmlElement]
public List<Coordinate> Coordinates { get; set; }
[XmlElement("action")]
public PlayerAction Action { get; set; }
}
public class PlayerAction
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAnyElement]
public XmlElement[] ActionContents { get; set; }
}
public enum Axis
{
[XmlEnum("x")]
X,
[XmlEnum("y")]
Y,
[XmlEnum("z")]
Z
}
public class Coordinate
{
[XmlAttribute("axis")]
public Axis Axis { get; set; }
[XmlText]
public double Value { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.