1

I have following object structure, deseralized from XML (WS):

<ns2:Category>
  <ns2:CategoryId>800003</ns2:CategoryId>
  <ns2:CategoryName>Name1</ns2:CategoryName>
  <ns2:Categories>
    <ns2:Category>
      <ns2:CategoryId>800008</ns2:CategoryId>
      <ns2:CategoryName>Name2</ns2:CategoryName>
      <ns2:Categories>
        <ns2:Category>
          <ns2:CategoryId>800018</ns2:CategoryId>
          <ns2:CategoryName>Name3</ns2:CategoryName>
          <ns2:Categories/>
        </ns2:Category>
        <ns2:Category>
          <ns2:CategoryId>800028</ns2:CategoryId>
          <ns2:CategoryName>Name4</ns2:CategoryName>
          <ns2:Categories/>
        </ns2:Category>
      </ns2:Categories>
    </ns2:Category>
    <ns2:Category>
      <ns2:CategoryId>800009</ns2:CategoryId>
      <ns2:CategoryName>Name5</ns2:CategoryName>
      <ns2:Categories>
        <ns2:Category>
          <ns2:CategoryId>800019</ns2:CategoryId>
          <ns2:CategoryName>Name6</ns2:CategoryName>
          <ns2:Categories>
            <ns2:Category>
              <ns2:CategoryId>800119</ns2:CategoryId>
              <ns2:CategoryName>Name7</ns2:CategoryName>
              <ns2:Categories/>
            </ns2:Category>
            <ns2:Category>
              <ns2:CategoryId>800219</ns2:CategoryId>
              <ns2:CategoryName>Name111</ns2:CategoryName>
              <ns2:Categories/>
            </ns2:Category>
          </ns2:Categories>
        </ns2:Category>
      </ns2:Categories>
    </ns2:Category>
  </ns2:Categories>
</ns2:Category>

How would I find Category object with CategoryId 800119 efficiently? So, Im looking for something like FindCategory(long categoryId) - Prefferably with LINQ to objects. Any other option?

1 Answer 1

3

I'd use LINQ to XML:

XNamespace ns = "http://url-for-ns2";
XDocument doc = XDocument.Load("file.xml");

string requiredId = "800119";
var categoryId = doc.Desendants(ns + "CategoryId")
                    .Where(x => x.Value == requiredId)
                    .FirstOrDefault();
var category = categoryId == null ? null : categoryId.Parent;
Sign up to request clarification or add additional context in comments.

2 Comments

Do you think that performace-wise is better to serialize the object and do the LINQ to XML. I have the object structure already cached.
It's unlikely that it's worth serializing back to XML, but you haven't shown what your object structure is like. I expect it wouldn't be hard to do something similar - particularly if they're partial classes so you can add a recursive call into Category.

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.