2

Hi I need to create an XElement from a string, which can be xml or plain string.

This code

    var doc = new XDocument(
        new XElement("results", "<result>...</result>")
    );

produces this

<results>&lt;result&gt;&lt;/result&gt;</results>

But if the string is XML, then I need proper XMl

<results><result>...</result></results>

Any ideas other than XElement.Parse() because it will throw exception if it is plain text?

CodeTower
  • 6,293
  • 5
  • 30
  • 54
Tushar Kesare
  • 700
  • 8
  • 20
  • 1
    tried `innerXML` yet? – EaterOfCode May 16 '13 at 11:42
  • You could test if the string is xml. E.g. it contains < and > if so use the parser, if not do something else (hard to tell what you wan't when its not XML) – CodeTower May 16 '13 at 11:45
  • I was going to say this is a duplicate of http://stackoverflow.com/questions/1414561/how-to-add-an-existing-xml-string-into-a-xelement, but the key point is "other than `XElement.Parse()`", which is actually my question too, if not for the same reasons – drzaus Jan 13 '14 at 18:01

3 Answers3

1

See my answer on Is there an XElement equivalent to XmlWriter.WriteRaw?

Essentially, replace a placeholder for the content only if you know it's already valid XML.

var d = new XElement(root, XML_PLACEHOLDER);
var s = d.ToString().Replace(XML_PLACEHOLDER, child);

This method may also be faster.

Community
  • 1
  • 1
drzaus
  • 24,171
  • 16
  • 142
  • 201
0

I don't know if there is other way around and it also doesn't look as a best way but you can achieve it like this:

object resultContent;

if (condition)
{
    //if content is XmlElement
    resultContent = new XElement("result", "....");
}
else
{
    resultContent = "Text";
}

XDocument xDoc = new XDocument(new XElement("results", resultContent));
Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
0

How about doing this:

XElement.Parse(String.Format("<Results>{0}</Results>",possibleXMLString));

... and before someone objects to this employing .Parse() method, which is mentioned by OP, please note that this is not the usage that was mentioned.

Tormod
  • 4,551
  • 2
  • 28
  • 50