2015-04-23 49 views
0

我目前正在嘗試爲基於XML的collada(.dae)文件導入一個導入程序。我將xml文件反序列化到可以輕鬆訪問的對象中。 例如,.dae文件可以具有這樣的設置...如何輕鬆遍歷反序列化的Xml文檔?

<library_geometries> 
<geometry id="Cube1s_008-mesh" name="Cube1s.008"> 
    <mesh> 
    <source id="Cube1s_008-mesh-positions"> 
     <float_array ...... /> 
    </source> 
    <source id="Cube1s_008-mesh-normals"> 
    </source> 
    <vertices id="Cube1s_008-mesh-vertices"> 
     <input semantic="POSITION" source="#Cube1s_008-mesh-positions"/> 
    </vertices> 
    </mesh> 
</geometry> 
<geometry> 
.... 
</geometry> 
</library_geometries> 

據(與xmlSerializer.Deserialize)以類似的方式,然後反序列化。因此,要訪問「網格」中的第二個「源」,我會做library_geometries.geometry [0] .mesh.source [1];

一切都很好,我遇到的問題很容易遍歷這個反序列化的XML文檔。

例如,在「頂點」中有一個source =「#Cube1s_008-mesh-positions」,其基本意思是「訪問頂點數據,去源ID爲」Cube1s_008-mesh-positions「 。我想要做的就是輕鬆地從頂點直接到源或任何具有該ID的任何東西。 所以它看起來像是library_geometries.geometry [0] .mesh.vertices.GoToSource();並與我可以做library_geometries.geometry [0] .mesh.vertices.GoToSource()。float_array.values;

我假設我需要用反射來做到這一點。 也許搜索任何具有[XmlAttribute(「id」)]的字段,然後以某種方式返回其正確類型的對象。 任何想法表示讚賞。

回答

0

您可以使用兩種基本方法。

1) Build a dictionary 
 
2) Add a new property Geometry geometry to the class veritices which is NonSerialize. After deserialize, enumerate through the classes adding the value to the property geometry.

+0

你的第二個方法類似於我一直在做的事情。我在名爲「sourceElement」的頂點類中添加了一個變量,這個變量可以直接引導我指向這個頂點所指向的源元素。要設置它,我必須做反射,獲取所有源,找到頂點指向的源並將其分配給sourceElement變量。問題是,我需要爲具有ID屬性的每種元素執行此操作。然後我開始試圖獲取任何具有ID屬性並存儲它的內容,但是當它存儲時,它是一個對象,並且不會以正確的類型存儲,從而使其不可用 – HiddenMonk

0

這就是爲什麼我喜歡的字典。我經常使用下面的類來嵌套結構。

public class Node 
 
{ 
 
    public string name { get; set; } 
 
    public List<Node> children { get; set; } 
 
    public Dictionary<string, string> dict { get; set; } 
 
}