简体   繁体   English

将XML反序列化为树

[英]Deserialise XML to Tree

I have the following XML data that I wish to build into a tree structure? 我希望将以下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>

What's the best way to parse this into a tree structure using LINQ? 使用LINQ将其解析为树结构的最佳方法是什么?

I'm assuming that I'll firstly need to start with a tree object such as the below: 我假设首先需要从一个树对象开始,如下所示:

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

select the encoding 选择编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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