2010-03-17 40 views
0

我有這樣的代碼:如何序列化爲包含屬性的XML?

... 
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服務器的答案。

+4

http://msdn.microsoft.com/en-us/library/182eeyhh.aspx。在問一個問題之前,請至少做一些研究。你會很快找到http://msdn.microsoft.com/en-us/library/2baksw0z.aspx,比等我告訴你更快。 – 2010-03-17 01:10:19

+0

我做了研究,我如何得到我的代碼。最有趣的事情 - 很多人使用不同的方法來生成/解析XML ...這就是爲什麼我在這裏問它。 – Andoriyu 2010-03-18 19:22:43

回答

0

如果您有一個描述您將從服務器接收的XML的XSD文件,那將是最好的。然後,您可以使用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; } 
} 
+0

以及如何使用該代碼生成和parese xml> – Andoriyu 2010-03-18 06:50:47