Reputation: 2049
XDocument doc = XDocument.Parse(_data)
XElement root = new XElement("student");
doc.Element("marks").Add(root);
doc.Save(_data)
the _data is the deserialized string xml and student is the root tag want to add doc.save throws the error.How to save the root tag ?
the string xml
<marks>
<name>Martin</name>
<date>3/24/2012</date>
<field>Percent</name>
<new>33.3</new>
<old>10</old>
</marks>
this is the string xml before root tag is added, once it is added it should look like after the root tag is added it should look like
<student>
<marks>
<name>Martin</name>
<date>3/24/2012</date>
<field>Percent</name>
<new>33.3</new>
<old>10</old>
</marks>
</student>
Upvotes: 0
Views: 5858
Reputation: 4418
How about:
var doc = new XDocument();
var root = new XElement("student");
var innerXml = XElement.Parse(_data);
root.Add(innerXml);
doc.Add(root);
_data = doc.ToString();
or alternatively
var doc = new XElement(
new XElement("student",
XElement.Parse(_data)
)
);
_data = doc.ToString();
or a one-liner:
_data = new XElement(new XElement("student", XElement.Parse(_data))).ToString();
Upvotes: 3
Reputation: 273179
XDocument.Parse(_data)
implies that _data
is XML, ie "<tag> <sub /> </tag>"
doc.Save(_data)
Requires _data
to be a valid filename. Like "output.xml"
Ok, seems that you need:
//doc.Save(_data)
_data = doc.ToString();
Take 3:
You need to add the existing xml to <Student>
, not the other way around.
//untested
XElement doc = XElement.Parse(_data); // not XDoc
XElement root = new XElement("student", doc);
//doc.Save(_data)
_data = root.ToString();
Upvotes: 4