将XML反序列化为树

时间:2011-12-03 13:20:09

标签: c# xml linq

我希望将以下XML数据构建到树结构中?

<DATA>
  <NODES>
    <NODE>
       <ID>1</ID>
       <CONTENT>Foo</CONTENT>
       <ChildrenIds>
           <Child>2</Child>
           <Child>3</Child>
       </ChildrenIds>
       <Level>1</Level>
    </NODE>
     <NODE>
       <ID>2</ID>
       <CONTENT>Foo</CONTENT>
       <ChildrenIds>
           <Child>4</Child>               
       </ChildrenIds>
    </NODE>
     <NODE>
       <ID>3</ID>
       <CONTENT>oo</CONTENT>
       <ChildrenIds>
         <Child>5</Child>
       </ChildrenIds>
    </NODE>
     <NODE>
       <ID>4</ID>
       <CONTENT>Doo</CONTENT>
       <ChildrenIds/>
    </NODE>
     <NODE>
       <ID>5</ID>
       <CONTENT>Koo</CONTENT>
       <ChildrenIds/>
    </NODE>
  </NODES>
</DATA>

使用LINQ将其解析为树结构的最佳方法是什么?

我假设我首先需要从树对象开始,如下所示:

public class Tree
{
    public Tree()
    {
        ChildrenNodes = new List<TreeStructure>();
    }

    public List<Tree> ChildrenNodes { get; set; }
    public int Id { get; set; }
    public string Content {get; set;}
}

1 个答案:

答案 0 :(得分:0)

usign system.runtime.serialization

[datacontract]
public class Tree
{
    public Tree()
    {
        ChildrenNodes = new List<TreeStructure>();
    }
    [datamember]
    public List<Tree> ChildrenNodes { get; set; }
    [datamember]
    public int Id { get; set; }
    [datamember]
    public string Content {get; set;}
}

void serialize(Tree tree,string filename)
{
datacontractserializer serializer = new datacontracetserializer (typeof(Tree));
system.xml.xmltextwriter writer = new xmltextwriter(filename,Encoding.UTF32);
serializer.WriteObject(writer,tree);
writer.close();
}

void deserialize(ref Tree tree,string filename)
{
    xmltextreader reader = new xmltextreader*new streamreader(filename, Encoding.UTF32));
DataContracetSerializer deser = new datacontracetserializer(typeof(Tree));
trr = (Tree)deserializer.readObject(reader);
reader.close()
}

选择编码