Rajneesh
Rajneesh

Reputation: 2089

can we build linq query over dynamically generated xml response?

I have one query over linq, suppose i have an xml response ( i am getting from some x server) each time this xml response will change but root element of xml is same but some times descendant nodes (like inside it have many different nodes) may exists or not, so i need to build linq query over this xml so that there will be no exceptions throws saying some x1 element or child node not exists..So finally it should take the xml (what come's from server response) and build the query.

Regards, Raj.

Upvotes: 0

Views: 151

Answers (2)

Serge Semenov
Serge Semenov

Reputation: 10052

First, you need to convert your XML to a dynamic structure. The first library I found (haven't tried though): https://www.nuget.org/packages/netfx-System.Xml.DynamicXml/
Then, you can add Linq on top of your dynamic XML root.
However, performance-wise this is really bad approach. I played once with dynamic XML and that was extremely slow. Maybe, instead of making it dynamic you can create extension methods to XElement (if you are loading the XML to XDocument) which will return empty node without throwing an exception, e.g. (pseudocode):

public static class XElementExtensions
{
  public static XElement SafeGetChild(this XElement node, string childName)
  {
    XElement result;
    if (!node.TryGetChildByName(childName, out result))
      result = node.Document.CreateElement(childName);
    return result;
  }
}

Upvotes: 0

edelwater
edelwater

Reputation: 2802

I had this in the past: xml's coming in with each time totally different structures.

So I build something that first analyzed the structure and stored this structure in database tables, to be able to also know the delta's and have some history (and diff-ing) on it. Since sometimes manual intervention is needed (can't predict everything).

After the analysis phase, then a query can be done on the new structure based on the structure analysis.

So I took a two step approach, maybe this is also applicable for you.

Upvotes: 1

Related Questions