C#XML XPATH无法将数据分配给数组以在ListView中显示它

时间:2012-11-17 12:28:15

标签: c# xml arrays xpath

我是C#和XML数据的新手。

我有以下xml数据。 此XML文件似乎没有与之关联的任何样式信息。文档树如下所示。

<response>
  <auctions>
   <auction>
    <id>90436</id>
    <user>blabla</user>
    <title>title name</title>
    <value>10000.00</value>
    <period>36</period>
    <www/>
   </auction>
   <auction>
    <id>90436</id>
    <user>blabla</user>
    <title>title name</title>
    <value>10000.00</value>
    <period>36</period>
    <www/>
   </auction>
  </auctions>
 </response>

我使用那个C#代码。 (它是Form1使用的类)

    public IXmlNamespaceResolver ns { get; set; }    

public string[] user,id,title,value,period;
    public void XmlRead(string url)
    {
                // Create a new XmlDocument  
                XPathDocument doc = new XPathDocument(url);
                // Create navigator  
                XPathNavigator navigator = doc.CreateNavigator();
                // Get forecast with XPath  
                XPathNodeIterator nodes = navigator.Select("/response/auctions", ns);

                int i = 0;
                foreach (XPathNavigator oCurrentPerson in nodes)
                {   
                    userName[i] = oCurrentPerson.SelectSingleNode("user").Value;
                    userId[i] = int.Parse(oCurrentPerson.SelectSingleNode("id").Value);
                    title[i] = oCurrentPerson.SelectSingleNode("title").Value;
                    value[i] = oCurrentPerson.SelectSingleNode("value").Value;
                    period[i] = oCurrentPerson.SelectSingleNode("period").Value;
                    i++; }
    }

我收到错误: 对象引用未设置为对象的实例。

  

userName [i] = oCurrentPerson.SelectSingleNode(“user”)。Value;

当我使用单个字符串变量时:userName,userId没有[]一切正常。

提前致谢

2 个答案:

答案 0 :(得分:1)

navigator.Select("/response/auctions/auction", ns);

答案 1 :(得分:1)

.Net是一个强类型的世界,因此使用它的好处。创建Auction类以保存xml中的数据:

class Auction
{
    public int Id { get; set; }
    public string User { get; set; }
    public string Title { get; set; }
    public decimal Value { get; set; }
    public int Period { get; set; }
    public string Url { get; set; }
}

用Linq将你的xml解析为Xml:

XDocument xdoc = XDocument.Load(path_to_xml_file);
IEnumerable<Auction> auctions =
    from a in xdoc.Descendants("auction")
    select new Auction()
    {
        Id = (int)a.Element("id"),
        User = (string)a.Element("user"),
        Title = (string)a.Element("title"),
        Value = (decimal)a.Element("value"),
        Period = (int)a.Element("period"),
        Url = (string)a.Element("www")
    };