使用选定的列表项构建XMLstring [英] Build a XMLstring using selected listitems

查看:78
本文介绍了使用选定的列表项构建XMLstring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个包含38个列表项的复选框列表,表列为"PerfCounter""ID"
IAM从数据库中检索的方式是:

Hi ,
I have a checkboxlist with 38 listitems,table columns are "PerfCounter" "ID"
The way iam retrieving from the database is:

DataTextField="PerfCounter"
DataValueField="ID"


我以&如果选择任何列表框,它将显示相应的值,并且后面的代码是:


I placed a lable in the form & if you select any listbox it will displays the corresponding value and the code behind is:

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = string.Empty;

    foreach (ListItem listitem in CheckBoxList1.Items)
    {
        if (listitem.Selected)
            Label1.Text += listitem.Value + "<br />";
    }
}


到现在为止一切正常.
问题:我只想使用选定的列表项(例如
)构建一个字符串


Till now it is working fine.
Issue:I just want to build a string with the selected listitems like

<Root><PC ID="1"/><PC ID="6"/><PC ID="12"/><PC ID="28"/></Root>


这样我就可以将该字符串用作存储过程的参数来设计报告.例如:


so that i can use that string as a parametr to my storedprocedure to design reports. Ex:

EXEC [Report].[usp_GetPermonCounterData] @ServerID = 543, @xmlDocument = '<Root><PC ID="1"/><PC ID="6"/><PC ID="12"/><PC ID="28"/></Root>'

推荐答案

如果您需要将xml作为字符串处理,则可以使用以下内容:
If you need to handle xml as string you could use something like this:
protected string GetAsXMLString(CheckBoxList itemsource)
{
    StringBuilder sb = new StringBuilder("<root>");

    foreach (ListItem listitem in itemsource.Items)
    {
        if (listitem.Selected)
            sb.Append(String.Format("<PC ID=""{0}""/>", listitem.Value));
    }
    sb.Append("</root>")
    return sb.ToString();
}


ZoltánZörgő给出的解决方案1很好.

如果要使用LINQ ,则可以使用以下查询将参数用作XML string
The Solution 1 given by Zoltán Zörgő is good.

If you want to use LINQ then the following query can be used to get parameter as an XML string
string paramValue = CheckBoxList1.Items.OfType<ListItem>().Where (li =>
    li.Selected).Aggregate ("<Root>",(string agg, ListItem li) =>
    agg += string.Format(@"<PC ID=""{0}""/>",li.Value)) + "</Root>";

//Sample paramValue
//<Root><PC ID="1"/><PC ID="6"/></Root>


使用xlinq:

Use xlinq:

var x = new XElement("Root",
    new XElement("PC", new XAttribute("ID", "1")),
    new XElement("PC", new XAttribute("ID", "6")),
    new XElement("PC", new XAttribute("ID", "12")),
    new XElement("PC", new XAttribute("ID", "28")));
//or
x.Add(new XElement("PC", new XAttribute("ID", "36")));
Console.WriteLine(x.ToString());


这篇关于使用选定的列表项构建XMLstring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆