Vincenzo Lo Palo
Vincenzo Lo Palo

Reputation: 1381

How to do a xml parsing

I have this xml file: http://www.studiovincent.net/list.xml

I need parser with c#, to get values. Im using this code:

XmlReader xmlReader = XmlReader.Create("http://www.studiovincent.net/list.xml");
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "field"))
            {
                if (xmlReader.HasAttributes)
                    Console.WriteLine(xmlReader.GetAttribute("name") + ": " + xmlReader.GetAttribute("price"));
            }
        }
        Console.ReadKey();

but I get in OUTPUT this result:

name:
username:
age:
hair:
name:
username:
age:
hair:
name:
username:
age:
hair:

How Can I get this result?

Vincent
Hill
31
black
John
Tedelon
27
brown
Michael
Lopez
20
red
Frank
Lopez
25
black

and this result?

 Vincent
 John
 Michael
 Frank

Thanks in advance!

Upvotes: 0

Views: 125

Answers (3)

ganesh
ganesh

Reputation: 1066

The following code will give you, your first result:

        using System.Xml;
        using.System.Xml.Linq;

        XmlReader reader = XmlReader.Create("http://www.studiovincent.net/list.xml");
        XElement el = XElement.Load(reader);
        reader.Close();

        var items = el.Elements("resources").Elements("resource").Descendants().DescendantNodes();

        foreach (XNode node in items)
        {
            Console.WriteLine(node.ToString());
        }

The following code will give you, your second result

        var items = from item in el.Elements("resources").Elements("resource").Descendants() where item.Attribute("name").Value == "name" select item.FirstNode;

        foreach (XNode node in items)
        {
            Console.WriteLine(node.ToString());
        }

Upvotes: 3

Colonel Panic
Colonel Panic

Reputation: 137524

These first two lines will help you:

using System.Xml.Linq;
var doc = XDocument.Load("http://www.studiovincent.net/list.xml");
var people = doc.Descendants("resource");

This library is called Linq for XML

Upvotes: 1

arunlalam
arunlalam

Reputation: 1838

You can use

string URL = "http://www.studiovincent.net/list.xml";
XDocument doc = XDocument.Load(URL);

//To read an element you use
 List<XElement> myElements = doc.Element("list").Element("resources").Elements("resource").Elements("field").ToList();

        foreach (XElement element in myElements)
        {

            Console.WriteLine("{0} : {1}", element.Attribute("name").Value, element.Value);


        } 

Upvotes: 0

Related Questions