Sandeep Polavarapu
Sandeep Polavarapu

Reputation: 382

Adding XML Content in string to XDocument

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?

Upvotes: 5

Views: 3350

Answers (2)

greenfeet
greenfeet

Reputation: 677

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);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503270

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)
    );
)

Upvotes: 6

Related Questions