【问题标题】:display xml using linq使用 linq 显示 xml
【发布时间】:2014-11-18 07:59:28
【问题描述】:
MessageBox.Show("Hi");

string xml = @"<Table>
                 <Product>
                   <Product_id>1</Product_id>
                   <Product_name>Product 1</Product_name>
                   <Product_price>1000</Product_price>
                 </Product>
                 <Product><Product_id>2</Product_id><Product_name>Product 2</Product_name><Product_price>2000</Product_price></Product>
                 <Product><Product_id>3</Product_id><Product_name>Product 3</Product_name><Product_price>3000</Product_price></Product>
                 <Product><Product_id>4</Product_id><Product_name>Product 4</Product_name><Product_price>4000</Product_price></Product>
               </Table>";
XDocument doc = XDocument.Parse(xml);

foreach (XElement element in doc.Descendants("Product_id"))
{
    Console.WriteLine(element);
}

单击按钮时,仅显示Hi MessageBox。元素不显示。

【问题讨论】:

  • 代码没问题(显示1到4)。你确定你真的在看控制台吗?如果您将 Console.Write 替换为 MessageBox.Show(例如“Hi”)会怎样?
  • 'System.Windows.Forms.MessageBox.Show(string)' 的最佳重载方法匹配在 Form1.cs 中有一些无效参数 .... 我使用 MessageBox.Show(element);显示元素..但它抛出错误..帮助我正确使用表格。我对 c# 很陌生
  • 简单解释,你必须调用element.Value而不是element,它是一个对象(XElement),“MessageBox.Show”不知道。 Console.WriteLine 更宽松。
  • MessageBox.Show(element.Value);这行得通..谢谢你:)
  • 不客气 :)。除了 Linq to XML,我建议您更彻底地了解什么是控制台以及应该在哪里显示它的消息。

标签: c# .net xml linq


【解决方案1】:

请试试这个。这些值将显示在控制台中。

 MessageBox.Show("Hi");
            string xml = @"
            <Table>
                <Product>
                    <Product_id>1</Product_id>
                    <Product_name>Product 1</Product_name>
                    <Product_price>1000</Product_price>
                </Product>
            <Product><Product_id>2</Product_id><Product_name>Product 2</Product_name><Product_price>2000</Product_price></Product>
            <Product><Product_id>3</Product_id><Product_name>Product 3</Product_name><Product_price>3000</Product_price></Product>
            <Product><Product_id>4</Product_id><Product_name>Product 4</Product_name><Product_price>4000</Product_price></Product>
            </Table>";
            XDocument doc = XDocument.Parse(xml);
            foreach (XElement element in doc.Descendants("Product_id"))
            {
                Console.WriteLine(element.Value);
            }

            Console.Read();

您应该致电Console.WriteLine(element.Value);

【讨论】:

  • 不工作。嗨消息框后没有显示任何内容
  • @Sherin Mathew > 正如我在第一条评论中所说,我认为 OP 根本看不到控制台。
  • @DhanushD > 正如我之前问过的,问题是您希望在哪里看到它?你了解什么是“控制台”吗???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
相关资源
最近更新 更多