在Microsoft REST XML响应中查找特定节点

时间:2015-03-24 20:14:06

标签: c# xml

我试图找到节点TravelDistance中的值,如图所示 但我也得到了Null 这是我的尝试

string url = @"https://dev.virtualearth.net/REST/V1/Routes?wp.0=43.104234, -77.627686&wp.1=43.103219, -77.621267&wp.2=43.100619, -77.624963&output=xml&distanceUnit=Mile&key= Ap5gFiZ56mvoqUXoswD2Hw81EZk5xMaCcP6JNzJOc-0xAf2wqTYgvSUZ8uhXJifZ";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(url);

            XmlNode nodea = xmlDoc.SelectSingleNode("/Response/ResourceSets/ResourceSet/Resources/Route/TravelDistance");

enter image description here

2 个答案:

答案 0 :(得分:2)

XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable);
mgr.AddNamespace("x", "http://schemas.microsoft.com/search/local/ws/rest/v1");
var dist = xmlDoc.SelectSingleNode("//x:Route/x:TravelDistance", mgr).InnerText;

答案 1 :(得分:0)

通过这种方式解决的问题

string url = @"https://dev.virtualearth.net/REST/V1/Routes?wp.0=43.104234, -77.627686&wp.1=43.103219, -77.621267&wp.2=43.100619, -77.624963&output=xml&distanceUnit=Mile&key= Ap5gFiZ56mvoqUXoswD2Hw81EZk5xMaCcP6JNzJOc-0xAf2wqTYgvSUZ8uhXJifZ";

            HttpWebRequest req = WebRequest.Create(url)
                                  as HttpWebRequest;
            string result = null;
            using (HttpWebResponse resp = req.GetResponse()  as HttpWebResponse)
            {
                StreamReader reader =
                    new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
              string TravelDistance = result.Substring(result.IndexOf("<TravelDistance>") + "<TravelDistance>".Length, (result.IndexOf("</TravelDistance>") - result.IndexOf("<TravelDistance>")) - "<TravelDistance>".Length);

如果有任何人有附加解决方案请说明