coder3521
coder3521

Reputation: 2646

How to Get The Values Printed from XML using LINQ or XPath

I am bit stuck in getting the values printed from the XML using XPath or LINQ also new to XPath and XML Parsing , Looked into couple of examples here but nothing helped as they all have XML with diffrent attribute names, For my case XML is diffrent :

<Entities TotalResult="3">
    <Entity Type="test-set-folder">
      <Fields>
          <Field Name="id">
            <Value>12457</Value>
          </Field>
          <Field Name="parent-id">
            <Value>0</Value>
          </Field>
          <Field Name="last-modified">
            <Value>2015-03-09 14:09:57</Value>
          </Field>
          <Field Name="description">
             <Value/>
          </Field>
          <Field Name="view-order"/>
          <Field Name="name">
            <Value>.NET</Value>
          </Field>
     </Fields>
   </Entity>
   <Entity Type="test-set-folder">
     <Fields>
        <Field Name="id">
           <Value>15487</Value>
        </Field>
        <Field Name="parent-id">
          <Value>0</Value>
        </Field>
        <Field Name="last-modified">
          <Value>2015-03-15 13:00:02</Value>
        </Field>
        <Field Name="description">
          <Value/>
        </Field>
        <Field Name="view-order"/>
        <Field Name="name">
          <Value>Python</Value>
        </Field>
     </Fields>
  </Entity>
</Entities>

It has same attribute Field but different Name .

Can Someone help me in printing the Name of property and its Value .

I need to iterate through each of the Entity and print its Name : Value.

So far i Have tried using Xpath and LINQ both :

var doc = XDocument.Load("XMLFile1.xml");
        foreach (var child in doc.Element("Field Name").Elements())
        {
            Console.WriteLine(child.Name);
        } 

But seriously i don't have much idea of it , so my approach is entirely wrong.

My Expected Output is :

Id: 12457
parent-id: 0
last-modified:2015-03-09 14:09:57
description:
view-order:
name: .NET

and same for the next entity .

Upvotes: 1

Views: 250

Answers (4)

jdweng
jdweng

Reputation: 34421

You have a pivot table since your data is extracted from two tags (Name & Value). Here is a way to parse the xml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Entity> cEntities = new List<Entity>();
            string input =
                "<Entities TotalResult=\"3\">" +
                    "<Entity Type=\"test-set-folder\">" +
                      "<Fields>" +
                          "<Field Name=\"id\">" +
                            "<Value>12457</Value>" +
                          "</Field>" +
                          "<Field Name=\"parent-id\">" +
                            "<Value>0</Value>" +
                          "</Field>" +
                          "<Field Name=\"last-modified\">" +
                            "<Value>2015-03-09 14:09:57</Value>" +
                          "</Field>" +
                          "<Field Name=\"description\">" +
                             "<Value/>" +
                          "</Field>" +
                          "<Field Name=\"view-order\"/>" +
                          "<Field Name=\"name\">" +
                            "<Value>.NET</Value>" +
                          "</Field>" +
                     "</Fields>" +
                   "</Entity>" +
                   "<Entity Type=\"test-set-folder\">" +
                     "<Fields>" +
                        "<Field Name=\"id\">" +
                           "<Value>15487</Value>" +
                        "</Field>" +
                        "<Field Name=\"parent-id\">" +
                          "<Value>0</Value>" +
                        "</Field>" +
                        "<Field Name=\"last-modified\">" +
                          "<Value>2015-03-15 13:00:02</Value>" +
                        "</Field>" +
                        "<Field Name=\"description\">" +
                          "<Value/>" +
                        "</Field>" +
                        "<Field Name=\"view-order\"/>" +
                        "<Field Name=\"name\">" +
                          "<Value>Python</Value>" +
                        "</Field>" +
                     "</Fields>" +
                  "</Entity>" +
                "</Entities>";


            XElement entities = XElement.Parse(input);

            foreach (XElement entity in entities.Descendants("Entity"))
            {
                Entity newEntity = new Entity();
                cEntities.Add(newEntity);

                foreach (XElement field in entity.Descendants("Field"))
                {
                    string name = field.Attribute("Name").Value;
                    string value = field.Element("Value") == null ? "" : field.Element("Value").Value;

                    switch (name)
                    {
                        case "id" :
                            newEntity.id = int.Parse(value);
                            break;
                        case "parent-id":
                            newEntity.parent_id = int.Parse(value);
                            break;
                        case "last-modified":
                            newEntity.last_modified = DateTime.Parse(value);
                            break;
                        case "description":
                            newEntity.description = value;
                            break;
                        case "view-order":
                            newEntity.view_order = value;
                            break;
                        case "name":
                            newEntity.name = value;
                            break;
                    }
                }
            }

            //write data
            foreach(Entity entity in cEntities)
            {
                Console.WriteLine("id: {0}", entity.id);
                Console.WriteLine("parent-id: {0}", entity.parent_id);
                Console.WriteLine("last-modified: {0}",entity.last_modified);
                Console.WriteLine("description: {0}",entity.description);
                Console.WriteLine("view-order: {0}",entity.view_order);
                Console.WriteLine("name: {0}",entity.name);
                Console.WriteLine();

            }
            Console.ReadLine();


        }
        public class Entity
        {
            public int id { get; set; }
            public int parent_id { get; set; }
            public DateTime last_modified { get; set; }
            public string description { get; set; }
            public string view_order { get; set; }
            public string name { get; set; }
        }
    }
}
​

Upvotes: 1

Bgl86
Bgl86

Reputation: 737

Since some Fields missing a Value element, you could try this:

XElement element = XElement.Load("XmlFile.xml"); 
var query = from field in element.Descendants("Field")
select new
{
    NameAttribute = field.Attribute("Name").Value,
    Value = field.Descendants("Value").Any() ?
    field.Element("Value").Value : "No Value"
};
var namesAndValues = query.ToList()

Upvotes: 2

Ajay
Ajay

Reputation: 6590

Try this

var names = from r in document.Descendants("Entities")
                                .Descendants("Entity")
                                    .Descendants("Fields")
                                        .Descendants("Field")
            select new
                {
                    Name = r.Element("name").Value,
                };

foreach (var n in names)
{
    Console.WriteLine(n.Name);
}

Upvotes: 0

Ceres
Ceres

Reputation: 3648

You just need to follow the structure of your xml

Untested code:

var doc = XDocument.Load("XMLFile1.xml");
foreach (var fields in doc.Descendants("Fields")) {

    foreach (var field in fields.Elements("Field")) {

        Debug.WriteLine(string.Format("{0}: {1}", field.Attribute("Name").Value, field.Elements("Value").First().Value));

    }

}

Upvotes: 0

Related Questions