Reputation: 3169
I have a object obj with 2 properties p1, p2. and a XElement like:
<root><AA><BB>BB</BB></AA></root>
I'd like to make my Xelement as:
<root><AA><BB>BB</BB><CC><p1>val1</p1><p2>val2</p2></CC></AA></root>
I make a new XElement from obj
XElement x = new XElement("CC",new XElement("p1", obj.p1),new XElement("p2", obj.p2));
and insert it in AA element. is ther a better way by serializing my obj and convert it to XElement? (Because My object can change in the future) . Thanks for any help. Here is my attempt to 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);
});
Upvotes: 0
Views: 778
Reputation: 21661
Since you're open to using XmlSerializer
, use the XmlRoot
attribute; try adding the following to your 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 for more information.
After that, you can use this 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 the desired output.
If you want to remove the XMLNS declarations, you can use .Attributes.Remove()
after creating the XElement.
Upvotes: 1