TiGreX
TiGreX

Reputation: 1816

How to improve loop Xdocument

I'm doing an example about how to read with c# and linq an .xml file, I read it but I think that the code is not good.

Any suggestion, or explanation how to do better is welcome.

XML:

<file>
 <order>
  <products>
    <product>
     <id>123</id>
     <Description>Camera</Description>
     <seller>Website</seller>
    </product>
    <product></product>
    <product></product>
  </products>
 </order>
</file>

And this is my code, I want to improve the part to take the description, this way doesn't looks nice.

var reader = XDocument.Load("file.xml");
var listProdcutsNodes = reader.Element("file").Element("order").Element("products").Elements("product").Select(input => input.Elements()).ToList();
var description = "";
foreach (var listProdcutsNode in listProdcutsNodes)
{
    var isproduct = false;
    foreach (var xElement in listProdcutsNode)
    {
        if (xElement.Name == "id" && xElement.Value == "123")
        {
            isproduct = true;
        }

        if (isproduct && xElement.Name == "Description")
        {
            description = xElement.Value;

        }

    }

    isproduct = false;
}

Upvotes: 0

Views: 52

Answers (2)

Kram
Kram

Reputation: 526

You can use Linq, Or Just regular XPath. This is the xpath for your xml :

//product[./*[text()='123']]/Description/text()

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26896

Getting all of nodes as list and iterating over them is redundant in your case.

You can get that description pretty easily like this:

string myID = "123";
var description = reader.XPathSelectElements("/file/order/products/product")
                .Where(x => x.Element("id").Value == myID)
                .Select(x => x.Element("Description").Value).FirstOrDefault();

Upvotes: 1

Related Questions