0

I'm getting a string from string GetXmlString(); this I cant change.

I have to append this to an xml within a new XElement ("parent" , ... ); , to the ... area.

This string I'm getting is of the following format.

<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
...

The final result I want is this to be like

<parent>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
<tag name="" value =""></tag>
...
</parent>

when I just pass the string as XElement("root", GetXmlString()) < and > are encoded to &lt; and &gt

When I try XElement.Parse(GetXmlString()) or XDocument.Parse(GetXmlString()) I get the There are multiple root elements exception.

How do I get the required output without escaping the brackets? What am I missing?

Dhanushka Dolapihilla
  • 1,115
  • 3
  • 17
  • 34

2 Answers2

5

The simplest option is probably to give it a root element, then parse it as XML:

var doc = XDocument.Parse("<parent>" + text + "</parent>");

If you need to append to an existing element, you can use:

var elements = XElement.Parse("<parent>" + text + "</parent>").Elements();
existingElement.Add(elements);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    My question was a bit misleading. I have done a little edit. I have to stick to the final result format given. also there are multipe `parent` elements too. Your solution adds another `root` element within the `parent ` element right? – Dhanushka Dolapihilla Apr 15 '15 at 06:38
  • 1
    @DanDole: No, it doesn't - it didn't have the `parent` element at all. All you had to do was change `root` to `parent`, and you have the complete results. No need for `new XElement("parent", ...)` at all, unless you need to add it to an *existing* element - which is still easy, but it's not clear from your question what you actually need. – Jon Skeet Apr 15 '15 at 07:12
2

An alternative to Jon's suggestion would be to create an XmlReader for your fragment and parse from that:

var element = new XElement("parent");

var settings = new XmlReaderSettings
{
    ConformanceLevel = ConformanceLevel.Fragment
};

var text = GetXmlString();

using (var sr = new StringReader(text))
using (var xr = XmlReader.Create(sr, settings))
{
    xr.MoveToContent();

    while (!xr.EOF)
    {
        var node = XNode.ReadFrom(xr);   
        element.Add(node);
    }
}

This would be useful if the 'parent' element already exists, else simple concatenation of the XML nodes at each end and parsing would be simpler.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45