Below is my code
private void ConvertXmlToClass()
{
try
{
XDocument doc = XDocument.Load(@"C:\Users\sana-user\Documents\Visual Studio 2015\Projects\SVGXMLToJsonApp\SVGXMLToJsonApp\File\3rect.svg");
string jsonText = JsonConvert.SerializeXNode(doc);
dynamic dyn = JsonConvert.DeserializeObject(jsonText);
dynamic svg = dyn.svg;
var result = new Svg
{
g = new List(),
svgStyle = GetString(svg, "@style"),
id = GetString(svg, "@id"),
x = GetString(svg, "@x"),
y = GetString(svg, "@y"),
viewBox = GetString(svg, "@viewBox"),
cssStyle = GetString(((IDictionary)svg)["style"] as ExpandoObject, "#text"),
};
foreach (ExpandoObject gObj in svg.g)
{
var g = new G
{
Id = GetString(gObj, "@id"),
};
if (IsPropertyExist(gObj, "rect"))
{
var rect = ((IDictionary)gObj)["rect"] as ExpandoObject;
g.Rect = new Rect
{
Class = GetString(rect, "@class"),
id = GetString(rect, "@id"),
height = GetString(rect, "@height"),
width = GetString(rect, "@width"),
x = GetString(rect, "@x"),
y = GetString(rect, "@y"),
};
}
if (IsPropertyExist(gObj, "text"))
{
var txt = ((IDictionary)gObj)["text"] as ExpandoObject;
g.Text = new Text
{
Class = GetString(txt, "@class"),
id = GetString(txt, "@id"),
TextData = GetString(txt, "#text"),
transform = GetString(txt, "@transform"),
};
}
result.g.Add(g);
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private string GetString(ExpandoObject obj, string key)
{
return ((IDictionary)obj)[key] as string;
}
private bool IsPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
Below is my class
public class Svg
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string viewBox { get; set; }
public string cssStyle { get; set; }
public string svgStyle { get; set; }
public List g { get; set; }
}
public class G
{
public string Id { get; set; }
public Rect Rect { get; set; }
public Text Text { get; set; }
}
public class Text
{
public string id { get; set; }
public string transform { get; set; }
public string Class { get; set; }
public string TextData { get; set; }
}
public class Rect
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string Class { get; set; }
public string width { get; set; }
public string height { get; set; }
}
and below is the XML data that i want to insert in database
1 Reply
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Ruchi SharavatPosted Oct 15, 2018, 2:13 AM