将Xml数据绑定到数据源绑定控件

前面我们说到了如何读取Xml的节点名称,属性值,文本元素值,那么将Xml数据绑定到数据源绑定控件就变得很简单了,我们知道数据源绑定控件的数据源都是集合(如:IList,ArrayList)或者是DataSet,DataTable等,我们直接从xml读取所有所需要的值加载到泛型集合或者DataSet,DataTable等中里面,然后将它们绑定到数据源绑定控件中(如GirlView,DataList)

下面看一个例子:

<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product id="0" proName="手机" proPrice="1200" proInfo="手机手机手机手机手机手机">
  </Product>
  <Product id="2" proName="mp4" proPrice="400" proInfo="mp4mp4mp4mp4mp4mp4mp4mp4mp4">
  </Product>
  <Product id="3" proName="mp41" proPrice="400" proInfo="mp4mp4mp4mp4mp4mp4mp4mp4mp4">
  </Product>
  <Product id="4" proName="mp5" proPrice="500" proInfo="mp5mp5mp5mp5mp5mp5mp5mp5mp5">
  </Product>
  <Product id="5" proName="传真机1" proPrice="100" proInfo="传真机,传真机" />
</Products>

 首先通过面向对象的思想对xml进行操作,将xml各个属性的值封装到类中,然后进行相关操作

     //读取xml数据到集合中

 public static DataTable GetProduct(string path)
        {
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.Load(path);
            XmlNode xmlNode = xmldocument.SelectSingleNode("Products");
            if (xmlNode==null)
            {
                return null;
            }
            if(xmlNode.ChildNodes.Count<=0)
            {
                return null;
            }
            DataTable dt = new DataTable();
            foreach (XmlAttribute att in xmlNode.ChildNodes[0].Attributes)
            {
                dt.Columns.Add(new DataColumn(att.Name,typeof(string)));
            }
            XmlNodeList nodeList = xmldocument.SelectNodes("/Products/Product");
            foreach (XmlNode xn in nodeList)
            {
                DataRow dr = dt.NewRow();
                foreach (DataColumn column in dt.Columns)
                {
                    dr[column] = xn.Attributes[column.ColumnName].Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

  //绑定数据

  public void produceDataBind()
    {
        this.Repeater1.DataSource = operateXml.GetProduct(XmlFilePath.Path).DefaultView;
        this.Repeater1.DataBind();
    }

 其次,我们也可以直接对xml进行操作,绑定的时候可以直接通过视图或者是DataSet的ReadXml方法绑定

视图:

或者在后台用DataSet的ReadXml方法绑定

   protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        string path = Server.MapPath("Product.xml");
        ds.ReadXml(path);
        this.GridView1.DataSource = ds;
        this.GridView1.DataBind();
    }

上面是我们绑定xml的两种思想和方法...

多思考,多创新,才是正道!
原文地址:https://www.cnblogs.com/shuang121/p/1965137.html