使用C#,如何逐行显示XML?

时间:2010-11-16 14:06:46

标签: c# xml listbox linq-to-xml

HY,

我有这个xml:

<books>
  <book1 name="Cosmic">
    <attribute value="good"/>
  </book1>
</books>  

如何逐行在listBox控件中显示它,最终结果是在这种情况下它是一个包含5行的列表框?

在这一刻,我正在使用LINQ to XML来填充XML:

 foreach (XElement element in document.DescendantNodes())
   {
     MyListBox.Items.Add(element.ToString());
   }

但最终结果将每个xml节点放在一个列表框项目中(包括子节点)。

有没有人知道如何在列表框项目中逐行放置xml?

感谢。

杰夫

3 个答案:

答案 0 :(得分:4)

一个简单的解决方案将使用如下的递归函数:

public void FillListBox(ListBox listBox, XElement xml)
{
    listBox.Items.Add("<" + xml.Name + ">");
    foreach (XNode node in xml.Nodes())
    {
        if (node is XElement)
            // sub-tag
            FillListBox(listBox, (XElement) node);
        else
            // piece of text
            listBox.Items.Add(node.ToString());
    }
    listBox.Items.Add("</" + xml.Name + ">");
}

当然,这个只打印标记名称(例如示例中为<book1>)而不打印属性(name="Cosmic"等)。我相信你可以把它们放在自己身上。

答案 1 :(得分:1)

如果要在列表框中显示原始XML,请使用文本流读取数据。

using(StreamReader re = File.OpenText("Somefile.XML"))
{
  string input = null;
  while ((input = re.ReadLine()) != null)
  {
    MyListBox.Items.Add(input);
  }
}

答案 2 :(得分:0)

杰夫,也许使用简单的TextReader.ReadLine()实现(以及读取/维护)要容易得多? 我不知道你想要实现什么,只是一个建议。