What is best way to search in XML document to retrieve one or more records against search criteria. Suggestions are welcomed.
Personally I'd use LINQ to XML if you possibly can. Your question is very vague at the moment, but for example, you could write:
XDocument doc = XDocument.Load("test.xml");
var matches = doc.Descendants("Person")
.Where(x => (string) x.Attribute("Name") == "Jon")
.Where(x => x.Elements("Child").Count() >= 2);
While you can use XPath, I generally prefer not to - it has all the normal problems of embedding one language within another, whereas using LINQ to XML you're using C# throughout, so you have no new syntax to learn - just the relevant methods within the LINQ to XML library.
LINQ to XML also makes namespace handling simple, and you don't need to worry about escaping values etc, as your query is all in code rather than in a string.
.net xml documents have good support for xpath.
It should work for most of your xml searches.
Take a look at XPath Examples
Use XPath by XmlDocument.SelectNodes or SelectSingleNode like this:
XmlDocument doc = new XmlDocument();
doc.Load("bookstore.xml");
XmlNode root = doc.DocumentElement;
// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");
// Select and display the first node in which the author's
// last name is Kingsolver.
XmlNode node = root.SelectSingleNode(
"descendant::bk:book[bk:author/bk:last-name='Kingsolver']", nsmgr);
Console.WriteLine(node.InnerXml);
Related
I have an XML document that i have deserialized according to my model class, now i want to convert it into an IEnumerable<XmlDocument> or IEnumerable<string> which is the return type of my function so i could return valid XML reply from my MVC REST API.
XmlDocument xml = new XmlDocument();
xml.LoadXml(responseStream);
XmlSerializer x = new XmlSerializer(typeof(mSchoolModel));
mSchoolModel mgp = (mSchoolModel)x.Deserialize(responseObj.GetResponseStream());
//return xml;
So can anyone help me how can i convert this into an IEnumerable?
Use the LINQ-to-XML API.
Convert your XmlDocument instance to an XDocument instance. Instructions available at: http://blogs.msdn.com/b/xmlteam/archive/2009/03/31/converting-from-xmldocument-to-xdocument.aspx
Use the Elements() or Descendants() methods on the XDocument instance to get an IEnumerable<XElement>
Transform the IEnumerable<XElement> to an IEnumerable<string> using the LINQ Enumerable.Select() operator.
Here's a simple example:
IEnumerable<string> elements
= XDocument
.Load(new XmlNodeReader(xml))
.Elements()
.Select(element => element.ToString());
*Note: since a valid XML document can only have one root node, the resulting collection from the example above won't be very interesting, but you should have enough here to get what it is that you need. If you're familiar with XPath, you may find it easier to get the elements you want using the XPath extensions to LINQ to XML. See: How To: Query LINQ to XML Using XPath
Update
Realized I may have read your question wrong. If you have an XmlDocument instance and you need to return an IEnumerable<XmlDocument> all you have to do is wrap the instance in a collection. For example,
IEnumerable<XmlDocument> xmlCollection = new XmlDocument[]{ xml };
Of course, this approach can be used for wrapping any object into a singleton collection of objects of the same type.
I have a Xml document that I want to convert into a XnlNodeList using a linq query. Now, neither Xml nor Linq are something know well. The error I'm getting is Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<System.Xml.XmlElement>' to 'System.Xml.XmlNodeList'. An explicit conversion exists (are you missing a cast?).
XmlNodeList abTestDocx = abTestDoc.GetElementsByTagName("FS").OfType<XmlElement>().OrderBy(FS => FS.GetAttribute("label"));
Thanks!
You don't generally create XmlNodeList instances yourself. Do you really need one though? If you just need to iterate over the nodes, just assign it to an IEnumerable<XmlElement>:
IEnumerable<XmlElement> abTestDocx = abTestDoc
.GetElementsByTagName("FS")
.OfType<XmlElement>()
.OrderBy(fs => fs.GetAttribute("label"));
Note that using LINQ to XML is generally nicer than the old XmlDocument API. Then you'd just need:
IEnumerable<XElement> abTestDocx = doc
.Descendants("FS")
.OrderBy(fs => (string) fs.Attribute("label"));
... and all kinds of other things would be simpler too. LINQ to XML is lovely :)
My application gets data from SharePoint web service (using SOAP and CAML query), I am using a Xdocument doc to store retrieved xmlNode and then assign xdocument to XMLDataSource which is binned to gridView.
Now I need to filter the Xdocument before binding, to pick only those records where an element (ows_Partner_x0020_Type) matches a variable.
I am trying like this :
doc = doc.Descendants(z + "row").Where(rows => rows.Attribute("ows_Partner_x0020_Type").Value == Partner_Type.SelectedValue);
or
var bar = doc.Descendants(z + "row").Where(rows => rows.Attribute("ows_Partner_x0020_Type").Value == Partner_Type.SelectedValue);
but the problem is that return type of above LINQ is System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>
which is quit nothing like XDocument, which is required format to bind to XMLDataSource as doc.ToString().
Hope I am able to explain the problem.
Thanks a lot in advance.
Vishal
If you're just trying to create a document with those elements, you can use:
XDocument filteredDocument = new XDocument(new XElement("root", bar));
(That will create a document with a root element of <root>, and all the elements you're interested in directly under that.)
Not quite sure about all the binding parts - I strongly suspect there may be a better alternative - but this will certainly give you a new XDocument.
This is driving me a little crazy. I am pulling an XML string from a database column and successfully creating an XDocument using XDocument.Parse. I've used linq to xml before to query xml trees but for some reason on this everything I am doing is returning null. Is it something to do with the namespace?
Here is a sampling of the text visualizer for my XDocument object:
// removed XML for privacy reasons
An example of the query I am trying:
XElement algorithmId = (from algoId in reportLogXml.Descendants(ALGORITHM_ID)
select algoId).FirstOrDefault();
I am using a constant for the string value and I have quadruple checked that the spelling matches as well as trying several different elements that are clearly in the document but they all return null. What am I doing wrong here?
Yes, it probably has to do with the namespace but also the <AlgorithmId> element has no descendants.
You can fix the ns problem like this:
//untested
XNameSpace ns0 = "http://schemas.datacontract.org/2004/07/Adapters.Adapter";
var ns1 = reportLogXml.Root.GetDefaultNamespace();
// check: ns0 and ns1 should be equal here
... in reportLogXml.Descendants(ns1 + ALGORITHM_ID)
Note that this is a special + operator, follow the format exactly.
I have several XDocuments that look like:
<Test>
<element
location=".\jnk.txt"
status="(modified)"/>
<element
location=".\jnk.xml"
status="(overload)"/>
</Test>
In C#, I create a new XDocument:
XDocument mergedXmlDocs = new XDocument(new XElement("ACResponse"));
And try to add the nodes from the other XDocuments:
for (ti = 0; (ti < 3); ++ti)
{
var query = from xElem in xDocs[(int)ti].Descendants("element")
select new XElement(xElem);
foreach (XElement xElem in query)
{
mergedXmlDocs.Add(xElem);
}
}
At runtime I get an error about how the Add would create a badly-formed document.
What am I doing wrong?
Thanks...
(I saw this question -- Merge XML documents -- but creating an XSLT transform seemed like extra trouble for what seems like a simple operation.)
You are very close. Trying changing the line
mergedXmlDocs.Add(xElem);
to
mergedXmlDocs.Root.Add(xElem);
The problem is that each XML document can only contain 1 root node. Your existing code is trying to add all of the nodes at the root level. You need to add them to the existing top level node instead.
I am not sure what programming language you are using, but for most programming languages there is extensive XML support classes. Most of them allow parsing and even adding of element. I would have 1 main file that I would keep around and then parse each new one adding the elements from the new one into the master.
EDIT: Sorry it looks like you are already doing exactly this.