日期:2014-05-20  浏览次数:20830 次

如何将读取xml文件中的内容作为数据源放到dropdownlist控件呢?
我有如下的xml文件,内容是
<CertificateType>
  <CerType>
  <TypeID>1</TypeID>
  <TypeName>专家证</TypeName>
  </CerType>
  <CerType>
  <TypeID>2</TypeID>
  <TypeName>中国居留证</TypeName>
  </CerType>
  <CerType>
  <TypeID>3</TypeID>
  <TypeName>出入境备案</TypeName>
  </CerType>
  <CerType>
  <TypeID>4</TypeID>
  <TypeName>护照</TypeName>
  </CerType>
</CertificateType>

如何通过linq to xml 的方式将TypeID,TypeName中的值放入到dropdownlist控件呢?小弟刚学linq,望各位大侠指教!

------解决方案--------------------
C# code
XElement root = XElement.Load(Server.MapPath("~/1.xml"));
var query = from f in root.Elements("CerType")
              select new { TypeID = f.Element("TypeID").Value, TypeName = f.Element("TypeName").Value };
DropDownList1.DataValueField = "TypeID";
DropDownList1.DataTextField = "TypeName";
DropDownList1.DataSource = query.ToList();
DropDownList1.DataBind();

------解决方案--------------------
C# code

            XDocument doc = XDocument.Load("c:\\1.txt");
            var vv = from r in doc.Descendants("CerType") select r;
            var vs = from r in doc.Descendants("CerType") select new { id = r.Element("TypeID").Value, name = r.Element("TypeName").Value };
            comboBox1.DisplayMember = "id";//或者是"name"
            comboBox1.DataSource = vs.ToArray();