从Xml数据内容中拆分一个值并添加下拉列表

时间:2016-02-01 11:37:00

标签: c# xml

 <?xml version="1.0" encoding="utf-8" ?>
 <Title>
   <subtitle>12,15,1,4 </subtitle>
 </Title >

这是我的xml structure,我需要拆分该值并将其添加到dropdownlist,但我在dropdownlist中获得了全部价值,请向我提供解决方案和我的代码是

private void bindxml()
{
    StreamReader str = new StreamReader(filepath);
    using (DataSet ds = new DataSet())
    {
        ds.ReadXml(filepath);
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "subtitle";
        DropDownList1.DataBind();
    }
}

2 个答案:

答案 0 :(得分:1)

DropDownList1.Items.AddRange(XElement.Load(filepath).Element("subtitle").Value
    .Split(',').Select(x => new ListItem(x)).ToArray());

加载XML,导航到&#34; subtitle&#34; element,使用逗号分隔符拆分该值,然后为每个元素创建一个新的ListItem。将此集合作为数组传递给DropDownList AddRange方法。

答案 1 :(得分:0)

使用以下代码:

string elements = string.Empty;
XmlDocument xml = new XmlDocument();
string xmlFilePath = Server.MapPath("XMLFile1.xml");  //File Name
xml.Load(xmlFilePath);

XmlNodeList companyList = xml.GetElementsByTagName("subtitle");

foreach (XmlNode node in companyList)
{
    XmlElement companyElement = (XmlElement)node;

    elements = companyElement.InnerText; 
}

List<int> subIds = new List<int>();
if (elements!="")
{
    subIds = elements.Split(',').Select(int.Parse).ToList();    
}

ddlSub.DataSource = TagIds;
ddlSub.DataBind();
ddlSub.Items.Insert(0, new ListItem("--Select Subtitle--", "0"));