问题描述
Hello CodeProject。
我的XML有点问题。试图创建一个可以显示不同城市温度的应用程序。
这是我的XML表格:
Hello CodeProject.
I have a slight problem with XML. Tried to create an application which could show temperatures in different cities.
This is my XML table:
<SERVERS>
<SERVER name="1">
<url>http://someeather.com/database.xml</url>
<search>xml/searchpath/here</search>
</SERVER>
<SERVER name="2">
<url>http://otherweather.com/database.xml</url>
<search>xml/searchpath/here</search>
</SERVER>
<SERVER name="3">
<url>http://anotherweather.com/database.xml</url>
<search>xml/searchpath/here</search>
</SERVER>
</SERVERS>
我必须做的是:
1.根据搜索节点获取每台服务器的温度
2.写出来。
我知道如何获取'responsedoc'并从服务器获取数据,我只是不知道如何分别为这些服务器中的每一个获取响应。
我的代码如下所示:
What I must do, is:
1. Get the temperature from each server, based on the search node
2. write it out.
I know how to get the 'responsedoc' and get the data from the server, I just don't know how to get the responsedoc for each one of these servers separately.
My code looks like this:
XmlNodeList urls = serverDoc.SelectNodes("//servers/server");
string id1 = "1;
string id2 = "2";
string id3 = "3";
foreach(XmlNode node in urls)
{
string server1 = node.Attributes["name"].InnerText; //Get the attribute name
//Check if attribute value matches the 'id' provided before foreach.
if (server1 == name1)
{
//Create new node list, so we can get the server url.
XmlNodeList urls2 = serverDoc.SelectNodes("//servers/server");
foreach (XmlNode node2 in urls2)
{
var serverPath = temp.InnerText; //Get the serverpath (the <search> node in .xml)
WebRequest request = WebRequest.Create(node2["url"].InnerText); //Get the nodes with the name <url>.
var response = request.GetResponse(); //Get a response from the server, based on the request node url, that matched the 'name' attribute with the 'id' before this code.
Stream stream = response.GetResponseStream(); //Create new stream from the external server for reading
XmlDocument responseDoc = new XmlDocument(); //Create new instance for a new xml document
responseDoc.Load(stream); //Create new xml document from the stream
var tempOut = responseDoc.SelectSingleNode(serverPath); //From this new document get the temperature based on the searchpath provided befre this code.
string temperature = tempOut.Attributes["value"].Value; //Now get the value from the attribute with the name 'value' from that new xml document, to set the temperature.
SetTemperature1(temperature); //Set the value on our method which sets this value on the templbl on our mainview.
}
}
}
因此,我为所有其他服务器获得相同的温度,但我需要不同的值每个(显而易见的)。我的代码可能有问题,但我不确定。
Because of this, I'm getting the same temperature for all the other servers, but I need different values for each (obvious). Might be something wrong with my code, but I'm not sure.
推荐答案
这篇关于获取多个节点XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!