简体   繁体   中英

How to Serialize to XML containing attributes?

I have this code:

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

I want to add attributes to some nodes and create some sub-nodes. Also how to parse xml like this:

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

It is not an XML file, it's an answer from HTTP server.

It would be best if you had an XSD file describing the XML you will be receiving from the server. You could then use the XSD.EXE program to produce .NET classes with the appropriate .NET attributes on them. You could then just use XmlSerializer.Deserialize .

I'm going to try to create such a class for you by hand. This will be a quick attempt, and may be wrong (I have to get back to work!)


Try this and see if it works.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM