【问题标题】:How to Serialize to XML containing attributes?如何序列化为包含属性的 XML?
【发布时间】:2011-01-28 09:23:13
【问题描述】:

我有这个代码:

...
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 服务器的响应。

【问题讨论】:

标签: c# xml mono xml-serialization unity3d


【解决方案1】:

最好有一个 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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多