繁体   English   中英

如何在C#中的TreeView中解析XML文件

[英]How to parse a xml file in treeview in c#

我有以下格式的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Performance>
  <transaction name="Home">
    <request transaction="Home">
      <URL>http://192.168.0.7:23267/</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>200</RESPONSE-CODE>
    </request>
    <request transaction="Home">
      <URL>http://192.168.0.7:23267/images/banner.JPG</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>200</RESPONSE-CODE>
    </request>
    <request transaction="Home">
      <URL>http://192.168.0.7:23267/favicon.ico</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>404</RESPONSE-CODE>
    </request>
  </transaction>
 <transaction name="Login">
    <request transaction="Login">
      <URL>http://192.168.0.7:23267/Login.aspx</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>200</RESPONSE-CODE>
    </request>
    <request transaction="Login">
      <URL>http://192.168.0.7:23267/images/banner.JPG</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>304</RESPONSE-CODE>
    </request>
    <request transaction="Login">
      <URL>http://192.168.0.7:23267/favicon.ico</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>404</RESPONSE-CODE>
    </request>
    <request transaction="Login">
      <URL>http://192.168.0.7:23267/Login.aspx</URL>
      <METHOD>POST</METHOD>
      <RESPONSE-CODE>302</RESPONSE-CODE>
      <Content-Type>application\x-www-url-encoded</Content-Type>
      <Request_Body>__VIEWSTATE=%2FwEPDwUKLTIyNjM0Mjg2OGRki4v1QSB8PsGDDRUcxLe8nvnfdRE%3D&amp;__VIEWSTATEGENERATOR=C2EE9ABB&amp;__EVENTVALIDATION=%2FwEWBAL985OpBAKNo6vIDwLIoPPsBAK63N3jDihcqbsKpbaFs%2FjuUd7THytQsuqK&amp;ctl00%24ContentPlaceHolder1%24username=aadi&amp;ctl00%24ContentPlaceHolder1%24password=aadi1234&amp;ctl00%24ContentPlaceHolder1%24log=Login</Request_Body>
    </request>
    <request transaction="Login">
      <URL>http://192.168.0.7:23267/securepage/SecurePage.aspx</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>200</RESPONSE-CODE>
    </request>
    <request transaction="Login">
      <URL>http://192.168.0.7:23267/images/banner.JPG</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>304</RESPONSE-CODE>
    </request>
  </transaction>
  <transaction name="Logout">
    <request transaction="Logout">
      <URL>http://192.168.0.7:23267/securepage/SecurePage.aspx</URL>
      <METHOD>POST</METHOD>
      <RESPONSE-CODE>302</RESPONSE-CODE>
      <Content-Type>application\x-www-url-encoded</Content-Type>
      <Request_Body>__VIEWSTATE=%2FwEPDwULLTIwMDIzMDY0MjdkZLJV17BO2R5dj5TTwq3Xxpx8sGBn&amp;__VIEWSTATEGENERATOR=0900BECB&amp;__EVENTVALIDATION=%2FwEWAgKd%2BtjcCAKA4sljkvXRoUoTS7vStAm0LmWvI9N4A0w%3D&amp;ctl00%24ContentPlaceHolder1%24Button1=Logout</Request_Body>
    </request>
    <request transaction="Logout">
      <URL>http://192.168.0.7:23267/securepage/Login.aspx</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>302</RESPONSE-CODE>
    </request>
    <request transaction="Logout">
      <URL>http://192.168.0.7:23267/Login.aspx?ReturnUrl=%2fsecurepage%2fLogin.aspx</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>200</RESPONSE-CODE>
    </request>
    <request transaction="Logout">
      <URL>http://192.168.0.7:23267/images/banner.JPG</URL>
      <METHOD>GET</METHOD>
      <RESPONSE-CODE>304</RESPONSE-CODE>
    </request>
  </transaction>
 </Performance>

我想解析该文件并读取每个交易标签属性作为Treeview的根,例如,Home将是Treeview的根节点,然后将URL标记值作为其子节点,并且所有交易和URL标记的相同之处意味着以root身份登录节点,而不是各自的URL标记值作为其子节点。

您可以使用命令行创建xml方案,然后创建cs类:

xsd xml.xml
xsd xml.xsd /c

这将产生xml.cs文件。 您可以使用常见的xml序列化器反序列化它。

    XmlSerializer ser = new XmlSerializer(typeof(Performance));
    var t = ser.Deserialize(new XmlTextReader(@"C:\temp\xml.xml"));

反序列化之后,您确实具有带有树结构的普通c#对象:

在此处输入图片说明

如果您在创建cs文件时遇到问题,则为:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.33440.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Performance {

    private PerformanceTransaction[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("transaction", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public PerformanceTransaction[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class PerformanceTransaction {

    private PerformanceTransactionRequest[] requestField;

    private string nameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("request", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public PerformanceTransactionRequest[] request {
        get {
            return this.requestField;
        }
        set {
            this.requestField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class PerformanceTransactionRequest {

    private string uRLField;

    private string mETHODField;

    private string rESPONSECODEField;

    private string contentTypeField;

    private string request_BodyField;

    private string transactionField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string URL {
        get {
            return this.uRLField;
        }
        set {
            this.uRLField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string METHOD {
        get {
            return this.mETHODField;
        }
        set {
            this.mETHODField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("RESPONSE-CODE", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string RESPONSECODE {
        get {
            return this.rESPONSECODEField;
        }
        set {
            this.rESPONSECODEField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Content-Type", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string ContentType {
        get {
            return this.contentTypeField;
        }
        set {
            this.contentTypeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Request_Body {
        get {
            return this.request_BodyField;
        }
        set {
            this.request_BodyField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string transaction {
        get {
            return this.transactionField;
        }
        set {
            this.transactionField = value;
        }
    }
}
XmlDocument xml = new XmlDocument();
            xml.Load("E://session1.xml"); // suppose that myXmlString contains "<Names>...</Names>"
            string roots = xml.DocumentElement.Name;
            treeView1.Nodes.Add(roots);
            TreeNode ParentNode = new TreeNode();
            XmlElement root = xml.DocumentElement;

            if (root.HasAttribute("name"))
            {
                {
                    String name = root.GetAttribute("name");
                    ParentNode.Text = name;
                    treeView1.Nodes.Clear();
                    treeView1.Nodes.Add(ParentNode);
                }
            }
            //while(xml.)
            XmlNodeList xnList = xml.DocumentElement.SelectNodes("/transaction/request");
            foreach (XmlNode xn in xnList)
            {

                string url = xn["URL"].InnerText;
                ParentNode.Nodes.Add(url);
                treeView1.ExpandAll();
            }

上面提到的代码可帮助ne生成具有第一个标签和标签值的树状视图,但不适用于第二个和第三个交易标签。这是继续进行的正确方法,还是我必须通过其他方法进行尝试。

使用XML Linq。 从此代码开始。 您可以对结果使用代码。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\\temp\\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); var results = doc.Descendants("transaction").Select(x => new { name = x.Attribute("name").Value, request = x.Elements("request").Select(y => new { transaction = y.Attribute("transaction").Value, URLs = y.Element("URL").Value }).ToList() }).ToList(); } } }​ 

或使用此代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
            const string FILENAME = @"c:\temp\test.xml";
        public Form1()
        {
            InitializeComponent();

            XDocument doc = XDocument.Load(FILENAME);
            TreeNode root = new TreeNode();
            treeView1.Nodes.Clear();

            foreach (XElement transaction in doc.Descendants("transaction"))
            {
                string name = transaction.Attribute("name").Value;
                TreeNode transactionNode = treeView1.Nodes.Add(name);

                foreach (XElement request in transaction.Elements("request"))
                {
                    string transactionName = request.Attribute("transaction").Value;
                    string URLs = request.Element("URL").Value;
                    string node = string.Format("Transaction : {0}, URL : {1}", transactionName, URLs);
                    transactionNode.Nodes.Add(node);
                }

            }

            treeView1.ExpandAll();
        }
    }
}
​

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM