2011-12-03 111 views
0

我希望將以下XML數據構建到樹結構中?將Deserialise 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;} 
} 
+0

有什麼實際問題? – Murph

+0

那麼ChildrenNodes呢?它們是否應該是一個帶有Id和內容以及子列表的列表的樹型?看起來不同您的類和xml樹結構。 – Shymep

+0

ChildrenNodes應該包含ChildrenIds中引用的節點。所以,在上面的XML中,我應該有一個Id = 1的Tree,並且這棵樹將有Id = 2和Id = 3的ChildrenNode,Id = 2的Child將有一個Tree = 4的ChildrenNode,依此類推樹 – user989046

回答

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

選擇編碼

+0

害怕這不會將ChildrenIds序列化爲樹節點。我正在尋找一種方法來實現特定的邏輯來處理這個問題? – user989046