How to use System.XML.Linq to read simple XML document? - c#

If I have added an XML document to a Visual Studio project, what code using System.XML.Linq will read data elements from this document?

The XDocument class is what you need to load an XML file
string myXmlFile = // path to your Xml file
XDocument myXmlDocument = XDocument.Load(myXmlFile);
It provides methods to query XML trees using LINQ queries, to manipulate in-memory XML trees and to create XML trees from scratch using functional construction

You also try XElement class
XElement doc = XElement.Load(xmlDataFilePath);

Related

Converting XML document into an IEnumerable

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.

How to use Xpath to insert into xml files

<feed>
<entry>
<data>1234</data>
<content>Stackoverflow</content>
</entry>
</feed>
Next data..
I have to create above xml using xpath in c# is this possible to do..
I had done xml file using below code
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"C:\Log_Data.xml");
XmlElement newelement = xmlDoc.CreateElement("entry");
XmlElement xmldata = xmlDoc.CreateElement("data");
XmlElement xmlcontent = xmlDoc.CreateElement("content");
xmldata.InnerText ="1234" ;
xmlcontent.InnerText ="Stackoverflow";
newelement.AppendChild(xmldata);
newelement.AppendChild(xmlcontent);
xmlDoc.DocumentElement.AppendChild(newelement);
xmlDoc.Save(#"C:\Log_Data.xml");
but i have to use Xpath like we do in sql to write queries like
"Insert into table............."
should it possible in .Net 2.0
XPath is a query language for XML documents. As such, it doesn't provide the capability to alter (delete or insert nodes) an XML document.
One of the most appropriate ways to create or alter an XML document (called XML transformation) is to use XSLT -- a language especially designed for XML transformations.
From C# one can use the .NET XslCompiledTransform class to perform any XSLT 1.0 transformation.
Third party .NET implementations exist for XSLT 2.0.
You have to create your own XPath parser to achieve this. Simple implementation of that can be found here.

Searching in XML Document

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);

Converting array of objects to XML in C#

I know there's no built in converter to convert an array of objects to XML. Is there a quick rudimentary way to create a XML out of the array to help me do a LINQ to XML join between this one and another XML I have?
You can use Linq to XML, it is really easy to map from your existing data structures to XML, i.e.:
int[] values = { 1, 2, 17, 8 };
XDocument doc = new XDocument();
doc.Add(new XElement("root", values.Select( x=> new XElement("item", x))));
produces the following output:
<root>
<item>1</item>
<item>2</item>
<item>17</item>
<item>8</item>
</root>
You can always use XmlSerializer to transform a list of C# objects to XML document. The result of the serialization may be customized by using metadata attributes to designate, for example, root nodes or which class property is to be ignored etc... You will definitely need to apply the attributes to make the resulting XML conform as much as possible to your requirements.
Here is a basic tutorial on serializing an Object to XML:

reading an XML string using LINQ

I am calling a sharepoint service /_vti_bin/usergroup.asmx from my silverlight app. In that the method GetAllUserCollectionFromWeb() returns the XML string. I need to iterate through that XML string to get the required data. But the LINQ to XML in this scenario is not working, as it is working when loading the XML file and getting the req data. How to do the similar functionality of LINQ to SQL with an XML string?
Sample code:
string str = #"<LanguageDetails>
<UserNode>
<Lang>
English
</Lang>
</UserNode>
</LanguageDetails>";
Need to handle the similar string and iterate to read the value using LINQ to XML.
You mean something like this?
string str = #"<LanguageDetails>
<UserNode>
<Lang>
English
</Lang>
</UserNode>
</LanguageDetails>";
XElement xLanguageDetails = XElement.Parse(str);
foreach (XElement xUserNode in xLanguageDetails.Elements("UserNode"))
{
}
In almost all cases where you return no rows when doing LINQ to XML queries, the reason is because there is a namespace in your XML. Check the root nodes to see if there are any namespaces and include them in your LINQ queries.

Categories