c0nfus3d
c0nfus3d

Reputation: 1450

Parse through XML

I've been reading through many tutorials and examples, but I'm lost. I have an XML file with this type of data:

<?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>

I'm trying to parse through this data in C# but having no luck at all. I have this:

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);
        }
    }

But nothing gets output in to my text box. :(

Upvotes: 1

Views: 151

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

You can use Linq to Xml to get properties from your 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"));
}

Upvotes: 2

Harold Sota
Harold Sota

Reputation: 7566

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);
            }
        }

Upvotes: 1

Related Questions