A. Wheatman
A. Wheatman

Reputation: 6378

Best practice to populate XElement with some text that containes XML nodes inside

what is the best way to populate XElement with the test that may contains not only the pure text but some XML nodes as well?

For example, this code

XElement el = new XElement("XML_NODE");
el.Value = "some text <TAG>with custom tag value</TAG>";
string xml = el.ToString();

will return xml as <XML_NODE>some text &lt;TAG&gt;with custom tag value&lt;/TAG&gt;</XML_NODE>. I understand what is going on and why it has happened. But it's not exactly what I want... I wish to get xml similar to this <XML_NODE>some text <TAG>with custom tag value</TAG></XML_NODE> where inner brackets are not quoted.

The desired result can be achieved by the next code

XElement el2 = XElement.Parse("<XML_NODE>some text <TAG>with custom tag value</TAG></XML_NODE>");
xml = el2.ToString();

but I don't like the idea to build XML as a string and parse it later.

Are there any other better ways to get it?

Upvotes: 0

Views: 234

Answers (2)

Richard Deeming
Richard Deeming

Reputation: 31198

Another alternative which might be slightly more efficient:

static IEnumerable<XNode> ParseNodes(string value)
{
   var settings = new XmlReaderSettings 
   { 
      ConformanceLevel = ConformanceLevel.Fragment 
   };

   using (var sr = new StringReader(value))
   using (var xr = XmlReader.Create(sr, settings))
   {
      xr.Read();
      while (xr.ReadState != ReadState.EndOfFile)
      {
         yield return XNode.ReadFrom(xr);
      }
   }
}

string text = "some text <TAG>with custom tag value</TAG>";
var node = new XElement("XML_NODE", ParseNodes(text));

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

As I said in my comment, there is really no better way. But you could encapsulate this "not so good" way somewhat:

public IEnumerable<XNode> ParsePartial(string partialXml)
{
    return XElement.Parse(string.Format("<tmp>{0}</tmp>", partialXml)).Nodes();
}

var el3 = new XElement("XML_NODE",
                       ParsePartial("some text <TAG>with custom value</TAG>"));

Upvotes: 1

Related Questions