2016-03-24 55 views
0

我想通過使用XmlSerializer讀取XML文件時遇到問題。 喜歡跟着我的xml文件:如何使用XmlSerializer讀取XML文件C#

<?xml version="1.0" encoding="utf-8"?> 
<contents> 
    <section id="1"> 
    <element1>2</element1> 
    <element2>1</element2> 
    <idx>1</idx> 
    <idx>2</idx> 
    <idx>3</idx>  
    </section> 

    <section id="2"> 
    <element1>2</element1> 
    <element2>1</element2>  
    </section> 

    <section id="3"/> 
</contents> 

這裏是類:

[Serializable()] 
public class section 
{ 
    [XmlAttribute("id")] 
    public string id { get; set; } 

    [XmlElement("element1")] 
    public int element1 { get; set; } 

    [XmlElement("element2")] 
    public int element2 { get; set; } 


    [XmlElement("idx")] 
    public int[] idx { get; set; } 


} 
    [Serializable()] 
    [XmlRoot("contents")] 
    public class contents 
    { 
     [XmlArray("section")] 
     [XmlArrayItem("section", typeof(section))] 
     public section[] section { get; set; } 
    } 

的反序列化功能:

   XmlSerializer serializer = new XmlSerializer(typeof(contents)); 


      FileStream fs = new FileStream(path, FileMode.Open); 
      XmlReader reader = XmlReader.Create(fs); 


      contents i; 


      i = (contents)serializer.Deserialize(reader); 
      fs.Close(); 




      foreach (section p in i.section) 
      { 
       Console.WriteLine(p.element1); 
      } 

爲什麼它不工作? 我參考了https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx,但它似乎沒有用。 請幫幫我!!!!!

+0

你提供了一些很好的信息,但是這似乎是重複的。在任何一種情況下,指定哪些內容不起作用通常是一個好主意 - 序列化中的例外情況?成員未按預期初始化?我的猜測是你有數組問題,因爲它們設置不正確。看到鏈接的問題。 –

回答

0

嘗試......

Usings ...

using System.Collections.Generic; 
using System.IO; 
using System.Xml.Serialization; 

類...

[XmlRoot(ElementName = "section")] 
    public class Section 
    { 
     [XmlElement(ElementName = "element1")] 
     public string Element1 { get; set; } 
     [XmlElement(ElementName = "element2")] 
     public string Element2 { get; set; } 
     [XmlElement(ElementName = "idx")] 
     public List<string> Idx { get; set; } 
     [XmlAttribute(AttributeName = "id")] 
     public string Id { get; set; } 
    } 

    [XmlRoot(ElementName = "contents")] 
    public class Contents 
    { 
     [XmlElement(ElementName = "section")] 
     public List<Section> Section { get; set; } 
    } 

代碼(使用http://xmltocsharp.azurewebsites.net/您的XML創建)...

 Contents dezerializedXML = new Contents(); 
     // Deserialize to object 
     XmlSerializer serializer = new XmlSerializer(typeof(Contents)); 
     using (FileStream stream = File.OpenRead(@"xml.xml")) 
     { 
      dezerializedXML = (Contents)serializer.Deserialize(stream); 
     } // Put a break-point here, then mouse-over dezerializedXML 

I把你的XML放在一個文件(xml.xml)中並從那裏讀取它......

+0

哦,它正在像我想要的那樣工作,非常感謝你<3 –