2012-09-28 218 views
0

我有一個XML像下面C#反序列化對象

 string input = 
@"<g1:Person xmlns:g1=""http://api.google.com/staticInfo/""> 
    <g1:Id>005008</g1:Id> 
    <g1:Infolist> 
<g1:Info><g1:Title>a</g1:Title></g1:Info>  
<g1:Info<g1:Title>b</g1:Title></g1:Info>  
<g1:Info><g1:Title>c</g1:Title></g1:Info> 
<g1:overview>there are three chaters.</g1:overview> 
    </g1:Infolist> 
    <g1:age>23</g1:age> 
    </g1:Person>"; 

我定義對象,但我不知道放在哪裏/人/ Infolist /概述。這個屬性如何定義。在哪裏放。

[XmlRoot(ElementName = "Person", Namespace = "http://api.google.com/staticInfo/")] 
    public class Person 
    { 

     public int Id { get; set; } 

     public int age { get; set; } 

     [XmlElement(ElementName = "Infolist", Namespace = "http://api.google.com/staticInfo/")] 
     public List<Info> Infolist {get;set; } 
    } 

    public class Info 
    { 
     public int Title { get; set; } 
    } 

回答

1
//------------------------------------------------------------------------------ 
// <auto-generated> 
//  This code was generated by a tool. 
//  Runtime Version:4.0.30319.269 
// 
//  Changes to this file may cause incorrect behavior and will be lost if 
//  the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

using System.Xml.Serialization; 

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1. 
// 


/// <remarks/> 
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
[System.SerializableAttribute()] 
[System.Diagnostics.DebuggerStepThroughAttribute()] 
[System.ComponentModel.DesignerCategoryAttribute("code")] 
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http:=//api.google.com/staticInfo/")] 
[System.Xml.Serialization.XmlRootAttribute(Namespace="http:=//api.google.com/staticInfo/", IsNullable=false)] 
public partial class Person { 

    /// <remarks/> 
    public ushort Id; 

    /// <remarks/> 
    public PersonInfolist Infolist; 

    /// <remarks/> 
    public byte age; 
} 

/// <remarks/> 
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] 
[System.SerializableAttribute()] 
[System.Diagnostics.DebuggerStepThroughAttribute()] 
[System.ComponentModel.DesignerCategoryAttribute("code")] 
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http:=//api.google.com/staticInfo/")] 
public partial class PersonInfolist { 

    /// <remarks/> 
    [System.Xml.Serialization.XmlElementAttribute("Info")] 
    public string[] Info; 

    /// <remarks/> 
    public string overview; 
} 

步驟:

  • 你的XML粘貼到Visual Studio中
  • 單擊XML新的XML文件 - >創建模式
  • 保存模式文件的磁盤
  • 開放visual studio命令提示符
  • 執行命令:xsd /classes /fields so.xsd

這可能是獲得結果的很多方法之一。我喜歡讓工具生成我的代碼 - 他們從不犯錯誤。

+0

自動生成?什麼是工具,man?我手動定義許多類 – user1682718

+0

xsd.exe是工具。你可以使用它的輸出來幫助你手動定義你的類。否則別人也許會回答你的問題太好了...祝你好運 –

+0

wow.awesome男人,謝謝你,發佈給我更多的知識 – user1682718