Converting array of objects to XML in C# - 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:

Related

Inserting XML nodes and inner nodes to an existing XML document in C#

Currently I have a working C# program that works as follows:
Accept .xls template with values (xls is manually created by user)
Save the values (matching fields) to the database
Convert and write .xls to XML. Please see below sample output:
Existing XML Structure
Now, what I want to do is:
Read the existing xml (the created xml)
Insert another set of nodes and subnodes (ReleaseLine and sub nodes). It must accept multiple ReleaseLine.
Save/create the new xml with appended nodes. Please see below output:
This is what I'm looking for:
My existing C# program is simple but the XML nodes and hierarchy is bloody deep. I just created the C# code using new XElement method and passing values for each nodes. Then I simply use xmlDocument.Save() method to write the xml.
[Existing XML Program][3]
To add nodes or append content in existing xml-data I´d use Linq to XML.
XElement xml = XElement.Load("file.xml");
xml.Add( new XElement("uberNode",
new XElement("childNode", content),
new XElement("anotherChildNode", content)));
xml.Save("file.xml");
Here are some other related solutions.
Add to specific node (with example):
Following exisiting XML-data:
`<Names>
<Name>
<prename>John</prename>
<lastname>Snow</lastname>
</Name>
<Name>
<prename>Harry</prename>
<lastname>Harry</lastname>
</Name>
</Names>`
Now I want to add an "age"-tag before the first "prename"-tag and a "family"-tag after the first "lastname"-tag.
XElement xml = XElement.Load("file.xml");
var childrens = xml.DescendantsAndSelf().ToArray();
var first_prename = childrens[2];
var first_lastname = childrens[3];
Console.WriteLine(childrens[0]); //prints out the whole content
first_prename.AddBeforeSelf(new XElement("age", 22));
first_lastname.AddAfterSelf(new XElement("family", new XElement("mother", "paula"), new XElement("father", "paul")));
xml.Save("file.xml");
Outcome:
`<Names>
<Name>
<age>22</age>
<prename>John</prename>
<lastname>Snow</lastname>
<family>
<mother>paula</mother>
<father>paul</father>
</family>
</Name>
<Name>
<prename>Harry</prename>
<lastname>Harry</lastname>
</Name>
</Names>`
I was facing the problem and Linq gave me the easiest way to accomplish that!
There are also other similar way e.g. here. But I tried a bit more and DescendantsAndSelf() made it easier for me to go through.
I found an answer to my question, here is the link http://www.xmlplease.com/add-xml-linq
Using XPathSelectElement method, I was able to find the right node and appended new block of XElement.

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.

Merging similar xml documents

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.

Creating a XmlDocument with hardcoded schema C#

I have an application that works with XML file. It works great if the xml file is present, however there is also a requirement, that the project generates a blank XML file and then writes to it in case the output file is not present.
The xml file has a quite complicated schema, something like the following:
<?xml version="1.0" encoding="UTF-8"?>
<Results>
<Result>
<WorkorderId>45</WorkorderId>
<WorkerId>13</WorkerId>
<DeviceId>38954178</DeviceId>
<Latitude>45.234</Latitude>
<Longitude>19.54</Longitude>
<Note>[all is good]</Note>
<Operations>
<Operation>
<OperationId>23</OperationId>
<Result>Success</Result>
<ParsedInformation>
<Info>parsed data</Info>
<Info>more parsed data</Info>
</ParsedInformation>
</Operation>
<!-- more operations ... -->
</Operations>
</Result>
<!-- more results ... -->
</Results>
I am wondering how would I create a XmlDocument like this, so I can write the results to it? Is there a "best practice" about hard coding the schema somewhere in the project, etc?
Please note that I am new to Xml so any additional information/literature would be very welcome.
I would usually create a set of classes that would contain the data and tag them with appropriate XmlSerializer attributes to make sure they get serialized to the format you are expecting. This is a pretty good resource: http://msdn.microsoft.com/en-us/library/2baksw0z(VS.85).aspx
In your case you would have the following classes (untested):
[XmlRoot("Results")]
public class Results
{
List<Result> results = new List<Result>();
[XmlElement("Result")]
List<Result> Results {get{return results;}}
}
public class Result
{
List<Operation> operations = new List<Operation>();
int WorkorderId {get; set;}
.... other fields
string Note{get;set;}
List<Operation> Operations {get{return operations;}}
}
public class Operation
{
List<string> parsedInformation = new List<string>();
int OperationId {get;set;}
....
[XmlArray("ParsedInformation")]
[XmlArrayItem("Info")]
List<string> ParsedInformation{get{return parsedInformation;}}
}
Later you use XmlSerializer class to serialize it to xml:
XmlSerializer serializer = new XmlSerializer(typeof(Results));
StringBuilder sb = new StringBuilder(); //this will contain the xml
serializer.Serialize(new TextWriter(sb), resultsObj);
Obviously you can also deserialize data from string to object.
Please note that if you have a XSD schema for your xml, you can use xsd.exe tool to generate the code for you.
If you actually have an XML Schema for your document format, then you can use the xsd.exe utility to generate a bunch of XmlSerializer-compatible classes for it - elements become classes, their attributes and children become properties, element sequences become collections, and so on. You'll also get proper types so long as your schema defines them (i.e. xs:int becomes int, and so on). Then you can build an object tree in memory using those classes, and serialize it using XmlSerializer.
To my knowledge you have to build the document node by node. Perhaps you can save an empty tree as template.

Categories