XML to BSON using C# - c#

I want to convert a XML file to BSON. then import the BSON to MongoDB. I searched but could not find how to covert this using C#. please provide me a source code to do this using C#

Had the same Problem today.
It's for sure not the best solution, but
i solved it this way in my project and it works for what i need it:
Deserialize XML to Json
Deserialize Json to Bson
using (var reader = new StreamReader(context.Request.Body))
{
var body = reader.ReadToEnd(); // read input string
XmlDocument doc = new XmlDocument();
doc.LoadXml(body); // String to XML Document
string jsonText = JsonConvert.SerializeXmlNode(doc); //XML to Json
var bsdocument = BsonSerializer.Deserialize<BsonDocument>(jsonText); //Deserialize JSON String to BSon Document
var mcollection = Program._database.GetCollection<BsonDocument>("test_collection_05");
await mcollection.InsertOneAsync(bsdocument); //Insert into mongoDB
}

Related

JSON output is not indented when using Formatting.Indented with SerializeObject

I'm trying to generate an indented JSON output using JSON.Net. The first code does not work
var data = new WebClient().DownloadString(url);
var json = JsonConvert.SerializeObject(data, Formatting.Indented);
However, this second code does work
var data = new WebClient().DownloadString(url);
var json = JValue.Parse(data).ToString(Formatting.Indented);
I'm a bit confused why both versions don't give the same output.

Converting XML to BsonArray in MongoDB using C#

I have an XML file and I want to convert to BsonArray in MongoDB, later then I can make it a list of elements. Here is what I tried.
XmlDocument doc = new XmlDocument();
doc.Load("Books.xml");
string json_doc = JsonConvert.SerializeXmlNode(doc);
...
using (var jsonReader = new JsonReader(json_doc))
{
var context = BsonDeserializationContext.CreateRoot(jsonReader);
var document = XML_collection.DocumentSerializer.Deserialize(context);
}
Code converts XML to Json but not BsonArray. That means what I will get is only ONE document with hundreds of fields. But what I want is making them separate as a list.
You can use BsonDocument.Parse() to read your string and then you can access catalog.book path to cast into BsonArray:
var json_doc = JsonConvert.SerializeXmlNode(doc);
var bsonArray = BsonDocument.Parse(json_doc)["catalog"]["book"].AsBsonArray;

How get JSON string from XML string using C#?

I am trying to convert XML string to C# object, I have json string acle in xml tag, as shown below,
<message> <data:gcm xmlns:data=\"google:mobile:data\">{\"message_type\":\"ack\",\"from\":\"sdhad4asd4a-sdasd45ds\",\"message_id\":\"-something\"}</data:gcm> </message>
I want json string from data tag I just want this string from above xml,
{\"message_type\":\"ack\",\"from\":\"sdhad4asd4a-sdasd45ds\",\"message_id\":\"-something\"}
So how can I get this using c#.?
Thank you in advance.
By reading some LINQ to XML documents I got the solution which is like below,
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(msg.ToString());
var result = xdoc.Element("message").Descendants();
var myString = result.FirstOrDefault().Value; //This will out given json string
Again Thank you #JonSkeet for your suggestion.!

Modifying element of Json string (in C#)

I'm trying to modify an attribute of an XML string using Json in C#. Currently I'm doing the following:
XmlDocument serializedFormXml = new XmlDocument();
serializedFormXml.LoadXml(mySerializedForm);
string formJsonString = JsonConvert.SerializeXmlNode(serializedFormXml, Newtonsoft.Json.Formatting.None, true);
JObject formJsonObj = JObject.Parse(formJsonString);
formJsonObj["#code"] = "myNewValue";
var xml = JsonConvert.DeserializeXmlNode(formJsonObj.ToString()).ToString();
When I do this I get get an exception on the last line:
Unable to cast object of type 'Newtonsoft.Json.Converters.XmlDocumentWrapper' to type 'Newtonsoft.Json.Converters.IXmlElement'
Any ideas what I'm doing wrong and how I can fix modify my form attribute "code"?
This is the XML I'm using:
<Form code="XYZ">
<Info>Data</Info>
.....
Thanks!
That's going to be way, way easier with Linq-to-XML:
var doc = XDocument.Parse(mySerializedForm);
doc.Root.SetAttributeValue(doc.Root.Name.Namespace + "code", "myNewValue");
var xml = doc.ToString();
This drops the XML declaration. If you need the XML declaration included, you can use the following extension method:
public static class XObjectExtensions
{
public static string ToXml(this XDocument xDoc)
{
using (var writer = new StringWriter())
{
xDoc.Save(writer);
return writer.ToString();
}
}
}
And then write:
var xml = doc.ToXml();
If specifically you need to make the encoding string say "UTF-8", use Utf8StringWriter from this answer.
Update
The reason you code fails is that you stripped the XML root element name away when you converted to json by passing true here:
string formJsonString = JsonConvert.SerializeXmlNode(serializedFormXml, Newtonsoft.Json.Formatting.None, true);
Thus you need to add it back when converting back:
var xml = JsonConvert.DeserializeXmlNode(formJsonObj.ToString(), serializedFormXml.DocumentElement.Name).ToString();

In .NET is there any way to convert an CSV value to XML based on predefined XML template?

I am using .NET and trying to convert an CSV data input (Example 1st row is header and following rows are the data: header1,header2,header3;row11,row12,row13;row21,row22,row23). Trying to convert this into XML format based on another XML template (there are multiple XML templates based on which the corresponding XML should be generated)
What is best practice to do this in .NET?
Sample template1:
<Claims>
<Claim>
<Header1></Header1>
<Header2></Header2>
<Header3></Header3>
</Claim>
</Claims>
Sample template2:
<Handlers>
<Handler>
<Header2></Header2>
<Header3></Header3>
<Header1></Header1>
</Handler>
</Handlers>
You should find a library that deserilizes CSV's then just serialize it into Xml using the XmSerializer.
Ie, using something like CsvHelper
var csv = new CsvReader( File.OpenText( "file.csv" ) );
var myCustomObjects = csv.GetRecords<MyCustomObject>();
Then get that resulting object and serialize into Xml:
XmlSerializer serializer = new XmlSerializer(typeof(MyCustomObject));
var subReq = new MyCustomObject();
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
serializer.Serialize(writer, subReq);
var xml = sww.ToString(); // Your xml

Categories

Resources