Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put in text when using XElement

Tags:

html

c#

linq

I'm using the new System.Xml.Linq to create HTML documents (Yes, I know about HtmlDocument, but much prefer the XDocument/XElement classes). I'm having a problem inserting   (or any other HTML entity). What I've tried already:

  1. Just putting text in directly doesn't work because the & gets turned int &. new XElement("h1", "Text to keep together.");

  2. I tried parsing in the raw XML using the following, but it barfs with this error:

    XElement.Parse("Text to keep together.");

    --> Reference to undeclared entity 'nbsp'.`

  3. Try number three looks like the following. If I save to a file, there is just a space, the   gets lost.


var X = new XDocument(new XElement("Name", KeepTogether("Hi Mom!")));
private static XNode KeepTogether(string p)`
{
    return XElement.Parse("<xml>" + p.Replace(" ", "&#160;") + "</xml>").FirstNode;
}

I couldn't find a way to just shove the raw text through without it getting escaped. Am I missing something obvious?

like image 997
Eric Avatar asked Feb 25 '09 19:02

Eric


2 Answers

I couldn't find a way to just shove the raw text through without it getting escaped.

Just put the Unicode character in that &nbsp; refers to (U+00A0 NO-BREAK SPACE) directly in a text node, then let the serializer worry about whether it needs escaping to &#160; or not. (Probably not: if you are using UTF-8 or ISO-8859-1 as your page encoding the character can be included directly without having to worry about encoding it into an entity reference or character reference).

new XElement("h1", "Text\u00A0to\u00A0keep\u00A0together");
like image 72
bobince Avatar answered Sep 22 '22 08:09

bobince


Replacing the & with a marker like ##AMP## solved my problem. Maybe not the prettiest solution but I got a demo for a customer in 10 mins so...I don't care :)

Thx for the idea

like image 41
Daniel Avatar answered Sep 24 '22 08:09

Daniel