2009-06-03 7 views
3

XML 문서를 반복하려고하는데 두 번째 반복에서 첫 번째 요소가 표시됩니다. 무엇이 빠졌는지 확실하지 않습니다. 누구든지 도와 줄 수 있습니까? XPath는xPath를 사용하여 항목을 반복합니다.

string file = HttpContext.Current.Server.MapPath("~/XML/Locations.xml"); 

    Dictionary<string, Location> locationCollection = new Dictionary<string, Location>(); 

     XPathDocument xDocument = new XPathDocument(file); 
     XPathNavigator xPathNavigator = xDocument.CreateNavigator(); 

     foreach (XPathNavigator node in xPathNavigator.Select("//locations/*")) 
     { 
      string value = node.SelectSingleNode("/locations/location/cell").Value; 
     } 



    <?xml version="1.0" encoding="utf-8" ?> 
<locations> 
    <location> 
    <locationName>Glendale</locationName> 
    <street>3717 San Fernando Road</street> 
    <city>Glendale</city> 
    <state>CA</state> 
    <zipcode>91204</zipcode> 
    <generalManager>DJ Eldon</generalManager> 
    <phone>(818) 552‐6246</phone> 
    <tollFree>(888) 600‐6011</tollFree> 
    <fax>(818) 552‐6248</fax> 
    <cell>(347) 834‐2249</cell> 
    <counterEmail>[email protected]</counterEmail> 
    <directEmail>[email protected]</directEmail> 
    </location> 
    <location> 
    <locationName>Chicago</locationName> 
    <street>1301 S. Harlem Ave.</street> 
    <city>Chicago</city> 
    <state>IL</state> 
    <zipcode>60402</zipcode> 
    <generalManager>Dave Schnulle</generalManager> 
    <phone>(708) 749‐1500</phone> 
    <tollFree>(888) 966‐1500</tollFree> 
    <fax>(818) 552‐6248</fax> 
    <cell>(708) 749‐3800</cell> 
    <counterEmail>[email protected]</counterEmail> 
    <directEmail>[email protected]</directEmail> 
    </location> 
</locations> 

답변

11

당신은 효과적으로 다시 문서 루트 얻기 위해 선도적 인 슬래시를 사용하여 node의 가치를 무시하고 예쁜 새. 대신 다음을 시도하십시오.

// This assumes that there are only location nodes under locations; 
// You may want to use //locations/location instead 
foreach (XPathNavigator node in xPathNavigator.Select("//locations/*")) 
{ 
    string value = node.SelectSingleNode("cell").Value; 
    // Use value 
} 

그렇다면 단일 XPath 쿼리에서 수행하지 않을 이유가 있습니까? , 그냥 빨리 해버 린

XPathNodeIterator ni = xPathNavigator.Select("//locations/*"); 
while (ni.MoveNext()) 
{ 
    string value = ni.Current.Value); 
} 

를 당신 도움이되기를 바랍니다 :

// Name changed to avoid scrolling :) 
foreach (XPathNavigator node in navigator.Select("//locations/location/cell")) 
{ 
    string value = node.Value; 
    // Use value 
} 
+0

감사합니다.이 기능은 훌륭했습니다 ... 예, 컬렉션에 다중 값을 추가하기 때문에 단일 xpath를 수행하지 않는 이유가 있습니다. 다시 한번 감사드립니다. – BoredOfBinary

0

는 다음을보십시오.

0

당신은 수행해야합니다

string value = node.SelectSingleNode("./cell").Value; 

을 당신은 xPathNavigator.Select 작업을 수행 할 때 ("// 위치/*") 당신이 아래로 하나 개의 요소를 이동해야하므로), 당신은 이미 내부/위치/위치에있어 예를 들어, 노드, 셀.

관련 문제