0

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;
}
2
  • Not quite sure what are you trying to achieve. Is is just "how to get description of product having some specified id"? Commented Jul 7, 2015 at 11:18
  • yes, just this, but trying to not use 2 lops and 2 ifs Commented Jul 7, 2015 at 11:21

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.