如何从xml C#中读取树

时间:2013-06-25 07:02:34

标签: c# xml

我有以下用于保存树的课程。

public class TreeNode
{
    private Dictionary<string, DataInfo> node;
    private List<TreeNode> children = new List<TreeNode>();
    ...
    ...
}

DataInfo就像:

public class DataInfo
{
    public Type Type { get; set; }
    public object Data { get; set; }
}

我在这个类中创建了一个方法,将这个树节点保存为XML。 XML看起来像:

<Tree>
  <Node>
    <Item Type="System.String">
      <Property>Name</Property>
      <Value>v1</Value>
    </Item>
    <Item Type="System.Int32">
      <Property>i</Property>
      <Value>1</Value>
    </Item>
    <Node>
      <Item Type="System.String">
        <Property>Name</Property>
        <Value>v2</Value>
      </Item>
      ...
      ...
      <Node>
          ...
          ...

如何解析此XML文件以读入我的TreeNode对象?任何线索/帮助都会有所帮助。

1 个答案:

答案 0 :(得分:0)

     XmlDataDocument xmlReaderDoc = new XmlDataDocument();
            FileStream xmlFileStream = new FileStream(F_ECAS_CONFIG.xlmfile_load_path, FileMode.Open, FileAccess.Read);
            xmlReaderDoc.Load(xmlFileStream);

            System.Xml.XmlElement root = xmlReaderDoc.DocumentElement;
            XmlNodeList messageList = root.GetElementsByTagName("Message");

            foreach (System.Xml.XmlNode message in messageList)
            {
                XmlNodeList childnodeList = message.ChildNodes;
                foreach (System.Xml.XmlNode childNode in childnodeList)
                {
                    if (childNode.InnerText.IndexOf("CAS MESSAGE") != -1)
                    {
                    }
                    else if (childNode.InnerText.IndexOf("casTextLine") != -1)
                    {
                        Cl_Ecas_ADE.textline_path.Add(childNode.InnerText); 
                    }
                    else if (childNode.InnerText.IndexOf("casLevel") != -1)
                    {

                        Cl_Ecas_ADE.cas_level_path.Add(childNode.InnerText);
                    }
                    else if (childNode.InnerText.IndexOf("casAckLine") != -1)
                    {
                        Cl_Ecas_ADE.ack_line_path.Add(childNode.InnerText);
                    }

                }
            }

它是一个示例示例,我在我的情况下尝试过它..根据您的代码进行修改...至少您将了解如何以XML格式读取树