Query xml with linq - c#

I am trying to query some informations from xml with linq but I am getting error like this - Yes I have defined - using System.Linq
Could you tell me, where is a problem?
Thanks
Error 1 Could not find an
implementation of the query pattern
for source type
'urn.P.IEEE.Item1671.Item2.Item2008.Item02.InstrumentDescription.InstrumentDescription'.
'Select' not found. D:\Documents and
Settings\e539951\my documents\visual
studio
2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 28 36 WindowsFormsApplication1
InstrumentDescription test = InstrumentDescription.Load(openFileDialog1.FileName);
var query = from b in test
select new { b.Identification };

In your code test represents just the root element of the document, so you can't use LINQ on it – it's not an sequence.
What you should do depends on how your XSD looks like. For example, if there can be multiple Identification elements under the root InstrumentDescription element, then just accessing test.Identitication gives you the list.

You're handling InstrumentDescription instead of an XDocument so it's probably that you need to make sure you InstrumentDescription class is IQueryable.
If you're actually wanting to do Linq against your XML, you either need to load it in as a dataset, or use Linq2XML (using System.Xml.Linq).
See more here. http://msdn.microsoft.com/en-us/library/system.xml.linq.aspx

Related

Dynamic LINQ query - passing string issue

I have a column named Rule in DB for storing one line of c# code, I want to retrieve them to.net program. The problem is, the retrieved line by lambda expression is not recognizable by .net program because of the c# class name in it. So is that the dynamical linq limit which can't implement it or not?
Expample 1:
Retrieved string from DB:
Regex.IsMatch(string.Concat(fieldValue1.Where(q => !Path.GetInvalidFileNameChars().Contains(q))), #"\d{11}")
Lambda Expr consuming the above retrieved string:
var result = fieldInfo.Where(RetrievedstringfromDB, Value)
The error is
No property or field 'Regex' exists in type 'XXX'
The closest thing I found that would do that is using Roslyn to run the whole thing dynamically, but to be fair that might not a good workaround for the project I am working on now, any lights/thoughts would be much appreciated!

Linq Check if a string contains any query from a list

I have a list of strings that are search Queries.
I want to see if a string from the database contains anyone of those terms in the Query. I'd like to do this on one line of code, that doesn't make multiple calls to the database. This should work but I want it to be more optimized.
var queries = searchQuery.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries).Distinct();
var query = context.ReadContext.Divisions.AsQueryable();
queries.ForEach(q => {
query = query.Where(d => (d.Company.CompanyCode + "-" + d.Code).Contains(q));
});
Is there a function that can do this better or a more optimal way of writing that?
There are two issues with your proposed solution:
Most LINQ to SQL providers don't understand string.Contains("xyz") so the provider will either throw an exception or fetch all the data to your machine. The right thing to do is to use SqlMethods.Like as explained in Using contains() in LINQ to SQL
Also, the code you show will check whether the division contains all of the specified strings.
To implement the 'any' behavior you need to construct a custom expression, which will not be possible using plain C#. You would need to look at the System.Linq.Expressions namespace: https://msdn.microsoft.com/en-us/library/system.linq.expressions(v=vs.110).aspx
It is possible, but quite involved.

Select all operations from a wsdl file using xpath

To autogenerate some documentation (and learn xpath) I am tring to get a list of all operations from a WSDL file.
What I have tried so far is:
doc = new XmlDocument();
doc.Load(#"C:\temp\tempuri.org.wsdl");
var list = doc.SelectNodes("wsdl:definitions/wsdl:portType/wsdl:operation");
This gives me the error:
Namespace Manager or XsltContext needed. This query has a prefix,
variable, or user-defined function.
Can anyone explain why I am getting this error and how to fix it?
I'd recommend taking a look at this answer: C# XPath help - Expression not working
You need to register the namespace wsdl before you start querying it.
e.g.:
XPathDocument xDoc = new XPathDocument(#"C:\temp\tempuri.org.wsdl");
XPathNavigator xNav = xDoc.CreateNavigator();
XmlNamespaceManager mngr = new XmlNamespaceManager(xNav.NameTable);
mngr.AddNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/"); // this namespace may need to be different - I don't know what your wsdl file looks like
XPathNodeIterator xIter = xNav.Select("wsdl:definitions/wsdl:portType/wsdl:operation",mngr);
Alternatively you can use LINQ to XML - see this answer from Jon Skeet: Namespace Manager or XsltContext needed
But you said you wanted to learn xPath so I guess it's irrelevant.

Converting Linq to XSLT

Is there a way to convert LINQ queries into XSLT? the same way LINQ can be converted to SQL?
I mean if i have a solid well defined XML(Conforms to an XSD) is there a way to compile the stuff under System.Linq.Expressions into XSLT in regard to that XML?
Thank you.
To Dimitries request I'll try to elaborate a little... Basically I have some data in one place (it's basically to chunks of xml serializable data), and I need to process them, I need to combine and process them.
Both the incoming original data , and the output result data, are XML serializable, and conform to a well defined XSD.
I want to generate the processing logic dynamically - someplace else. And allow my user to change and play around with the processing. I can represent the processing it self easily with Expression trees. Expression trees are similar to parse trees and can capture program code. This is the way linq to SQL works it converts expression trees to SQL queries.
Since all the income data and the output are both a well defined XML I can do the transformation easily with XSLT, but I'm not familiar with XSLT enough to write a dynamic XSLT generator. So I thought I could build the transformations in C# and convert them into XSLT.... again its not general purpose C#, but probably specific queries over a well defined data provider.
For the example sake:
(Not real code)
var schemas = XSchemaSet.Load("a","b");
var doc = XDocument.Load("File",schemas);
var result = from node in doc.Nodes
where node.Name == "Cats" || node.Name == "Dogs"
select (new Node(){Name = "Animal Owner", Value = node.Owner)
var newDoc = new XDocument().AddNodes(result);
newDoc.Validate(schemas);
Basically I want something that will function like that... I can write that in a single linq query if I use IQueryable.Aggregate
Yes, you can implement your own query provider, which uses XSLT internally, if you can figure out how to query with XSLT.
Why not just use Linq2XML?
It operates on XDocument and XElement
or alternatively if you want people to define transforms using xlst why not just execute an xslt against the document in code?
I dont see how having a Linq2XSLT would help solve a problem without recreating it in a different form

xml parsing in C#

Hi Guys
I would like to parse the following xml string in C#
i tried reading the entire string into the dataset and then using it .. there are simply no tables in the dataset.
here is the xml that I am interested to parse.
xml code is here
http://pastebin.com/VfT2wAwY
C# code is here
http://pastebin.com/iwqDK2S6
Thanks and regards,
Gagan Janjua
Have you considered LINQ to XML? If you're using .NET Framework 3.5 or later, then LINQ can save you a lot of time.
I haven't tested this, but you could do something like:
XDocument doc = XDocument.Load(#"C:\mydocument.xml");
var allCases = doc.Element("response").Element("cases").Descendants("case");
foreach (var currentCase in allCases) {
// I can now access each case specifically
var allEvents = currentCase.Descendants("events");
foreach (var currentEvent in allEvents) {
// now I can access each event
int ixBugEvent = (int)currentEvent.Element("ixBugEvent");
// etc...
}
}
Are you aware of XmlReader from System.Xml?
There is no schema in XML that you have provided, so you cannot expect that you can use it to populate DataSet... Unless you define your own schema, that is.
Your code is returning null because of your catch is making it null. It hits the catch, with the following error:
Column name 'ixBugEvent' is defined for different mapping types.
I have the impression that the reason for it is that you have ixBugEvent as both an attribute and a element
<event ixBugEvent='3' ixBug='2'>
<ixBugEvent>3</ixBugEvent>
Removing one of them fix the issue. The code is working, but your xml schema cannot be translated to a dataset.
You can change Scott's code to make it work by changing the following line of code:
// I can now access each case specifically
var allEvents = currentCase.Descendants("events");
Make it:
// I can now access each case specifically
var allEvents = currentCase.Descendants("event");
Doing that you have access to each event element. And from there you can definitely have access to ixBugEvent element.
I hope this helps.
P.s.: Sorry to make this another answer, but I would like to highlight the code, and it seems the only way to do it...

Categories

Resources