由於對象圖可能是循環的,因此您無法制作出基於樹的結構。最好的辦法是用最簡單的組件來表示對象圖:節點和向量。
更具體地說,使每個節點(對象)具有唯一ID的元素(可能由C#的GetHashCode()方法提供?)。引用其他對象(向量)將通過引用對象的ID來處理。
實例類(請注意,我不知道C#,所以我的語法可能有點關閉):
public class SomeType {
public int myInt { get; set; }
}
public class AnotherType {
public string myString { get; set; }
public SomeType mySomeType { get; set; }
}
public class LastType {
public SomeType mySomeType { get; set; }
public AnotherType myAnotherType { get; set; }
}
public class UserTypes{
static void Main()
{
LastType lt = new LastType();
SomeType st = new SomeType();
AnotherType atype = new AnotherType();
st.myInt = 7;
atype.myString = "BOB";
atype.mySomeType = st;
lt.mySomeType = st;
lt.myAnotherType = atype;
string xmlOutput = YourAwesomeFunction(lt);
}
}
然後我們希望xmlOutput的值是這樣的(注意,ID選擇的值是完全人工合成的):
<ObjectMap>
<LastType id="0">
<mySomeType idref="1" />
<myAnotherType idref="2" />
</LastType>
<SomeType id="1">
<myInt>7</myInt>
</SomeType>
<AnotherType id="2">
<myString>BOB</myString>
<mySomeType idref="1" />
</AnotherType>
</ObjectMap>
@jammycakes:將剛剛的「穿透曲線與XSLT」是一個有用的答案給你?如果是的話,我會擴展它。 – 2008-12-16 18:15:31