Read xml file/string in a generic way without knowing the structure

前端 未结 5 1968
终归单人心
终归单人心 2021-01-07 09:00

I want to read a XML hierarchy into a tree of in-memory objects. The XML tree could have n-levels of children. I do not know the exact number. My in-memory objects have a ch

5条回答
  •  萌比男神i
    2021-01-07 09:42

    I believe it is possible to achieve what you want to achieve. I'd do it something like this:

    class GenericNode
    {
      private List _Nodes = new List();
      private List _Attributes = new List();
      public GenericNode(XElement Element)
      {
         this.Name = Element.Name;
         this._Nodes.AddRange(Element.Elements()
                                     .Select(e => New GenericNode(e));
         this._Attributes.AddRange(
                    Element.Attributes()
                           .Select(a => New GenericKeyValue(a.Key, a.Value))
      }
    
      public string Name { get; private set; }
      public IEnumerable Nodes
      {
        get
        {
           return this._Nodes;
        }       
      }
      public IEnumerable Attributes
      {
        get
        {
           return this._Attributes;
        }
      }
    }
    
    class GenericKeyValue
    {
      public GenericKeyValue(string Key, string Value)
      {
         this.Key = Key;
         this.Value = Value;
      }
      public string Key { get; set; }
      public string Value { get; set; }
    }
    

    Then you simply:

    XElement rootElement = XElement.Parse(StringOfXml); // or
    XElement rootElement = XElement.Load(FileOfXml);
    
    GenericNode rootNode = new GenericRode(rootElement);
    

提交回复
热议问题