如何将项目添加到ListBox或XML中的其他控件? ASP.Net(C#)

时间:2011-03-24 11:48:12

标签: c# asp.net linq-to-xml

我的XML文件具有以下结构:

<rule ID="16" Attribute="Savvy" Parametr="">
      <body>
        <term Operation="AND">
          <IF_ID>8</IF_ID>
          <Ratio>=</Ratio>
          <IF_Value>impossible</IF_Value>
        </term>
        <term Operation="OR">
          <IF_ID>9</IF_ID>
          <Ratio>=</Ratio>
          <IF_Value>yes</IF_Value>
        </term>
        <term Operation="AND">
          <IF_ID>8</IF_ID>
          <Ratio>!=</Ratio>
          <IF_Value>impossible</IF_Value>
        </term>
        <term>
          <IF_ID>9</IF_ID>
          <Ratio>=</Ratio>
          <IF_Value>no</IF_Value>
        </term>
      </body>
      <value>normal savvy</value>
    </rule>

我需要将它添加到Listbox并获得1行:

8 = impossible AND 9 = yes OR 8 != impossible AND 9 = no - normal savvy

1 个答案:

答案 0 :(得分:1)

如果您需要知道如何通过XDocument读取属性,那么就像执行xElement.Attribute("Operation")

一样简单

现在要实际获得你想要的字符串结构,你需要做的就是遍历你的术语并将它们附加到一个字符串。

var xDocument = XDocument.Parse(x);
var stringBuilder = new StringBuilder();
foreach (var xElement in xDocument.Descendants("term"))
{
    var operationValue = xElement.Attribute("Operation") == null ? string.Empty : xElement.Attribute("Operation").Value;
    stringBuilder.AppendFormat("{0} {1} {2} {3} ", 
                                    xElement.Element("IF_ID").Value, 
                                    xElement.Element("Ratio").Value,
                                    xElement.Element("IF_Value").Value,
                                    operationValue);
}
stringBuilder.AppendFormat("- {0}", xDocument.Descendants("value").First().Value);

这假设您将为每个元素设置一个值,并且只有一个<rule/>。需要进行空检查才能使每个元素更正。

  

8 =不可能和9 =是或8!=   不可能和9 =没有 - 正常的精明

现在,这与列表框的关系我不确定,可能需要更多详细信息?

var item = new ListItem(stringBuilder.ToString());
listBox.Items.Add(item);

???