c# - Handling CData in converting Xml to Json using Newtonsoft -
i'm trying convert xml json , run business logic , deserialize c# object using newtonsoft json.net. xml has cdata values. how can deserialize json such value inside cdata mapped c# field.
edit: xml may/maynot contain cdata
e.g. xml:
with cdata
<?xml version="1.0" encoding="utf-8"?> <root> <text><![cdata[sample text]]></text> </root>
with plain text
<?xml version="1.0" encoding="utf-8"?> <root> <text>sample text></text> </root>
json:
with cdata:
{"text":{"#cdata-section":"sample text"}}
with plain text:
{"text":"sample text"}
code:
class data { [jsonproperty("text")] public string text { get; set; } } public static data convertjsontoobject(string json) { return jsonconvert.deserializeobject<data>(json); }
thank advance.
xsd xml sample. defined cdata simple type extending string , complex type text node containing cdata.
<xs:element name="root" type="cdata_text" /> <xs:simpletype name="cdata"> <xs:restriction base="xs:string"/> </xs:simpletype> <xs:complextype name="cdata_text"> <xs:sequence> <xs:element name="text" type="cdata" /> </xs:sequence> </xs:complextype>
generated cs file xsd:
namespace q38072488.xml { using system; using system.xml.serialization; [serializable()] [xmlroot("root", namespace = "", isnullable = false)] public partial class cdata_text { [xmlelement("text")] public string text { get; set; } } }
json classes:
namespace q38072488.json { using newtonsoft.json; public class cdatatext { [jsonproperty("#cdata-section")] public string cdata_section { get; set; } } public class rootobject { [jsonproperty("text")] public cdatatext text { get; set; } } }
deserialize xml , convert json (you add implicit conversion):
using (var fs = file.openread("cdata.xml") ) { var srlz = new xmlserializer(typeof(xml.cdata_text)); var xmlcdatatext = (xml.cdata_text)srlz.deserialize(fs); var ro = new json.rootobject() { text = new json.cdatatext() { cdata_section = xmlcdatatext.text } }; string json = jsonconvert.serializeobject(ro); }
Comments
Post a Comment