通过XML解析

时间:2013-10-02 16:11:21

标签: c# xml xml-parsing

我一直在阅读许多教程和示例,但我迷路了。我有一个包含此类数据的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);
        }
    }

但没有任何内容输出到我的文本框中。 :(

2 个答案:

答案 0 :(得分: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"));
}

答案 1 :(得分: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);
            }
        }