Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 470
  • Last Modified:

Using linq to get data out of an XML...

I have an xDocument that I am trying to get data out of.  I need to get two elements:
packageid
expectedweight

I am trying to use linq and I am having a hard time.  I want to loop through each package and grab these values and add them to my list of objects.

Here is what I have so far.
lstContainers = new List<EntityContainer>();

            var xmlParse = XElement.Parse(xmlDoc.ToString());

            var packages = from p in xmlDoc.Descendants()
                         where p.Name.LocalName == "package"
                         select p;

            XNamespace xns = xmlParse.Name.Namespace;

            if (packages != null && packages.Count() > 0)
            {
                foreach (var p in packages)
                {
                    EntityContainer objContainer = new EntityContainer();

                    objContainer.strContainerID = xmlParse.Descendants(xns + "packageid").Single().Value;
                    objContainer.dblTotalWeight = Convert.ToDouble(xmlParse.Descendants(xns + "expectedweight").Single().Value);

                    lstContainers.Add(objContainer);
                }
            }

Open in new window

xmlTest.xml
0
Bran-Damage
Asked:
Bran-Damage
  • 2
1 Solution
 
Bran-DamageAuthor Commented:
I figured out what I was doing wrong.  in the foreach i was still trying to use xmlParse.  I need to replace that with p...

The last question I have with this is this the best way to do what I am trying to do with linq.  Seems like a lot of code to get it.
0
 
brutaldevCommented:
Ignore the name space stuff, your XML doesn't contain any of that. You can also avoid the LINQ query because the Descendants has an overload for the name. I would also avoid the parse in the beginning, you can access the elements directly off the package XElement object. The count is also overkill, if it's not null then you can go straight to the loop.

Something like this (untested):
 
lstContainers = new List<EntityContainer>();

var packages = xmlDoc.Descendants("package");

if (packages != null)
{
  foreach (var p in packages)
  {
    EntityContainer objContainer = new EntityContainer();

    objContainer.strContainerID = p.Element("packageid").Value;
    objContainer.dblTotalWeight = Convert.ToDouble(p.Element("expectedweight").Value);

    lstContainers.Add(objContainer);
  }
}

Open in new window

0
 
Bran-DamageAuthor Commented:
Cool, thanks!
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now