Traversing an arbitrary C# object graph using XPath/applying XSL transforms

后端 未结 4 485
孤独总比滥情好
孤独总比滥情好 2021-01-04 09:21

I\'ve been looking for a component that would allow me to pass an arbitrary C# object to an XSL transform.

The naive way of doing this is to serialise the object gra

4条回答
  •  别那么骄傲
    2021-01-04 09:41

    Since the object graph may be cyclic, you cannot possibly make a Tree-based structure out of it. Your best bet is to represent the object graph by it's simplest components: nodes and vectors.

    More specifically, make each node (object) an element with a unique ID (perhaps provided by C#'s GetHashCode() method?). References to other objects (vectors) would be handled by referencing the ID of the object.

    Example classes (note that I don't know C# so my syntax may be a bit off):

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

    Then we would expect the value of xmlOutput to be something like this (note that the ID values chosen are completely synthetic):

    
     
       
       
     
    
     
      7
     
    
     
      BOB
      
     
    
    

提交回复
热议问题