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?

3
  • 1
    tried innerXML yet? Commented May 16, 2013 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) Commented May 16, 2013 at 11:45
  • I was going to say this is a duplicate of stackoverflow.com/questions/1414561/…, but the key point is "other than XElement.Parse()", which is actually my question too, if not for the same reasons Commented Jan 13, 2014 at 18:01

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.