Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding XML Content in string to XDocument

Tags:

c#

xml

I have to make an xml like this and post to a url on fly

<Student>
<Name>John</Name>
<Age>17</Age>
<Marks>
    <Subject>
        <Title>Maths</Title>
        <Score>55</Score>
    </Subject>
    <Subject>
        <Title>Science</Title>
        <Score>50</Score>
    </Subject>
</Marks>
</Student>

string marksxml = "<Marks><Subject><Title>Maths</Title><Score>55</Score></Subject><Subject><Title>Science</Title><Score>50</Score></Subject></Marks>";
XDocument doc = new XDocument(new XElement("Student",
new XElement("Name", "John"),
new XElement("Age", "17")));

What needs to be done to embed the string marksxml into XDocument?

like image 909
Sandeep Polavarapu Avatar asked Jun 19 '15 06:06

Sandeep Polavarapu


2 Answers

Just parse marksxml as an XElement and add that:

XDocument doc = new XDocument(
    new XElement("Student",
        new XElement("Name", "John"),
        new XElement("Age", "17"),
        XElement.Parse(marksxml)
    );
)
like image 134
Jon Skeet Avatar answered Oct 05 '22 17:10

Jon Skeet


1.First get rid of this tag

</Student>

in marksxml, because it will give you an exception when you parse.

string marksxml = "<Marks><Subject><Title>Maths</Title><Score>55</Score></Subject><Subject><Title>Science</Title><Score>50</Score></Subject></Marks>";

2.Then you create an XElement out of your string:

XElement marks = XElement.Parse(marksxml);

3.Now you add your new XElement to the student doc:

doc.Root.Add(marks);
like image 45
greenfeet Avatar answered Oct 05 '22 18:10

greenfeet