2

After creating an xml file using XDocument I end up with:

<![CDATA[text]]>

and

<br />

But I want to keep these as HTML, how do I stop this?

2
  • A curious mix of XML and HTML, in both code and text. Commented Oct 9, 2013 at 12:41
  • Nothing I can do about it, the data contains the html in the string. I wasn't aware of the new XCData() option though. Commented Oct 9, 2013 at 12:49

1 Answer 1

1

I assume you are passing a string to an XDocument or XElement constructor somewhere, where that string contains XML. Don't. Instead, use XDocument.Parse(string) or XElement.Parse(string).

See http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.parse.aspx and http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.parse.aspx

Note that this will only work for HTML that happens to be well-formed XML, obviously.

For example:

XElement.Parse("<TagName>The string has <br /> in it.</TagName>")

If you statically know the text, just build it up using constructor calls, e.g.

new XElement("TagName", "The string has ", new XElement("br"), " in it.")
Sign up to request clarification or add additional context in comments.

5 Comments

I actually found that using: new XElement(elementName, new XCData(value)); Resolves the CData issue, so instead of using Parse is there a simple add method for a line break in XDocument that adds the tag <w:br/>?
sure, Add(new XElement("br")) or the overload with a namespace
Sorry you've slightly confused me, let's say I create an element like so: new XElement("TagName","The string has <br /> in it"); How would I replace the <br />? surely not with just br?
Doesn't like: new XElement.Parse? Do I have to write as: new XElement(XElement.Parse(etc?
Either use new XElement(...), either XElement.Parse(...) without the new.

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.