0

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などの単一の文字列変数を[]なしで使用すると、すべてが正しく機能しました。

前もって感謝します

4

2 に答える 2

1
navigator.Select("/response/auctions/auction", ns);
于 2012-11-17T12:32:01.600 に答える
1

.Net は厳密に型指定された世界なので、その利点を利用してください。AuctionXML からのデータを保持するクラスを作成します。

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 to 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")
    };
于 2012-11-17T12:54:18.987 に答える