c# - Add Object to existing Xelement -
i have object obj 2 properties p1, p2. , xelement like:
<root><aa><bb>bb</bb></aa></root>
i'd make xelement as:
<root><aa><bb>bb</bb><cc><p1>val1</p1><p2>val2</p2></cc></aa></root>
i make new xelement obj
xelement x = new xelement("cc",new xelement("p1", obj.p1),new xelement("p2", obj.p2));
and insert in aa element. ther better way serializing obj , convert xelement? (because object can change in future) . help. here attempt use xmlserializer:
xelement xelem = reqret.requestdefinition; xelem.descendants("aa").tolist().foreach(reqitem => { using (memorystream ms = new memorystream()) { using (textwriter tw = new streamwriter(ms)) { xmlserializer ser = new xmlserializer(typeof(obj)); ser.serialize(tw, objval); schelem = new xelement( xelement.parse(encoding.ascii.getstring(ms.toarray()))); reqitem.add(schelem); } } reqitem.add(schelem); });
since you're open using xmlserializer
, use xmlroot
attribute; try adding following class declaration:
[xmlroot(namespace = "www.contoso.com", elementname = "cc", datatype = "string", isnullable=true)] public class myobj { ...
see https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute%28v=vs.110%29.aspx more information.
after that, can use code:
xelement xelem = xelement.parse("<root><aa><bb>bb</bb></aa></root>"); myobj myobj = new myobj(); xmlserializer ser = new xmlserializer(typeof(myobj)); foreach (xelement reqitem in xelem.descendants("aa")) { using (memorystream ms = new memorystream()) { ser.serialize(ms, myobj); reqitem.add(xelement.parse(encoding.utf8.getstring(ms.toarray()))); } }
this gives desired output.
if want remove xmlns declarations, can use .attributes.remove()
after creating xelement.