解析XML并显示消息框不起作用

时间:2019-05-12 02:32:13

标签: c# winforms

我有以下XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Store>
  <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>
</Store>

下面有以下代码,其中显示了每个产品的消息框:

private void Button2_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("e:\\product.xml");
        XmlNodeList nodes = doc.DocumentElement.SelectNodes("/Store/Product");
        string product_id = "", product_name = "", product_price = "";
        foreach (XmlNode node in nodes)
        {

            product_id = node.SelectSingleNode("Product_id").InnerText;
            product_name = node.SelectSingleNode("Product_name").InnerText;
            product_price = node.SelectSingleNode("Product_price").InnerText;
            MessageBox.Show(product_id + " " + product_name + " " + product_price);
        }
    }

但是由于某种原因,代码上升到foreach (XmlNode node in nodes),然后停止。没有显示错误或任何东西。我尝试调整一些东西,但没有任何帮助。我在.NET Framework 4.7.2上开发。

1 个答案:

答案 0 :(得分:0)

您的问题在这一行:

XmlNodeList nodes = doc.DocumentElement.SelectNodes("/Store/Product");

“ Store”不是XML文件中的节点,因此它将直接跳过foreach语句。将“商店”更改为“表”,您就可以开展业务。