2012-11-17 3 views
0

Im new in C# 및 XML 데이터 ussage.C# XML XPATH는 데이터를 배열에 할당하여 ListView에 표시합니다.

다음 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] [user]와 같은 단일 문자열 변수를 사용했을 때 모든 것이 올바르게 수행되었습니다. 사전

답변

1

닷넷에서

덕분에 강력한 형식의 세계, 그래서 혜택을의 사용합니다.

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을 구문 분석 : 당신의 XML 데이터를 개최 Auction 클래스를 만듭니다

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") 
    }; 
+1

덕분에 나는 XML을 C#을 데이터로 LINQ를 사용하는 방법을 배울 필요가있다. 그러나 나는 그것을 끝내는 더 좋고 더 간단한 방법이라고 생각한다. –

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