簡體   English   中英

在 Button_Click 事件中從 XML 文件中獲取數據

[英]Get data from an XML file in a Button_Click event

我正在嘗試使用以下代碼從 XML 文件中獲取數據:

private void button1_Click(object sender, EventArgs e)
{
    XDocument doc = XDocument.Load(@"C:\..\WindowsFormsApp10\stores.xml");
    var xpath = "//store[Color='Pink']";
    var result = doc.XPathEvaluate(xpath);
    textBox1.Text = result.ToString();
}

我的 XML 是:

<stores>
    <store rollNumer="170">
        <Name>Jonh</Name>
        <Color>Pink</Color>
        <Sell>Sugar</Sell>
    </store>

    <store rollNumer="120">
        <Name>Tedy</Name>
        <Color>Brown</Color>
        <Sell>Rice</Sell>
    </store>
</stores>            <!-- Added by edit -->

但它給了我這個錯誤:

System.Xml.XPath.XPathEvaluator+EvaluateIterator>d__1`1[System.Object]

我能做什么?

它的打印, System.Xml.XPath.XPathEvaluator+EvaluateIterator>d__1 1[System.Object]` 因為您正在打印對象。 在對象上使用 ToString() 不會打印對象的所有屬性; 相反,它使用 ToString() 方法打印對象的類型。

當您應該檢查顏色的 text() 為粉紅色時,您正在使用的 XPath 正在尋找“某物”為粉紅色的顏色。

這將奏效,

XDocument doc = XDocument.Load(filename);
var xpath = "//store/Color[text() = 'Pink']";
var result = ((IEnumerable)doc.XPathEvaluate(xpath)).Cast<XElement>().FirstOrDefault();
Console.WriteLine(result.Value);

打印以下輸出:

Pink

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM