1

我一直在阅读许多教程和示例,但我迷路了。我有一个包含此类数据的 XML 文件:

<?xml version="1.0"?>
<properties>
  <property>
    <name>Client Property A</name>
    <phone>Client Property A Phone Number</phone>
  </property>
  <property>
    <name>Client Property B</name>
    <phone>Client Property B Phone Number</phone>
  </property>
  <property>
    <name>Client Property C</name>
    <phone>Client Property C Phone Number</phone>
  </property>
</properties>

我试图在 C# 中解析这些数据,但一点运气都没有。我有这个:

XmlTextReader xmldata = new XmlTextReader("http://url.to/xml");
   XmlNodeList xmllist = doc.GetElementsByTagName("property");
   processList( xmllist );

public void processList(XmlNodeList xmllist)
    {
        // Loop through each property node and list the information
        foreach (XmlNode node in xmllist)
        {
            XmlElement nodeElement = (XmlElement)node;
            txtBox.AppendText(nodeElement.GetElementsByTagName("name")[0].InnerText);
            txtBox.AppendText(nodeElement.GetElementsByTagName("phone")[0].InnerText);
        }
    }

但是没有任何东西输出到我的文本框中。:(

4

2 回答 2

2

您可以使用 Linq to Xml 从您的 xml 中获取属性:

var xdoc = XDocument.Load("http://url.to/xml");

foreach(var p in xdoc.Root.Elements("property"))
{
   txtBox.AppendText((string)p.Element("name"));
   txtBox.AppendText((string)p.Element("phone"));
}
于 2013-10-02T16:15:14.683 回答
1
var m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";
string xmlStr;
using(var wc = new WebClient())
{
    xmlStr = wc.DownloadString(m_strFilePath);
}
var doc= new XmlDocument();
doc.LoadXml(xmlStr);

    XmlNodeList xmllist = doc.SelectNodes("//property");
       processList( xmllist );


    public void processList(XmlNodeList xmllist)
        {
            // Loop through each property node and list the information
            foreach (XmlNode node in xmllist)
            {
                XmlElement nodeElement = (XmlElement)node;
                txtBox.AppendText(nodeElement.SelectSingleNode("name").InnerText);
                txtBox.AppendText(nodeElement.SelectSingleNode("phone").InnerText);
            }
        }
于 2013-10-02T16:16:32.483 回答