Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

asp.net - How to avoid System.Xml.Linq.XElement escaping HTML content?

I'm using the XElement object to build some HTML in the code-behind on an ASP.NET page.

I may or may not add some XAttributes to this XElement as I go along, in the following fashion:

var elmnt = new XElement("div",
     new XAttribute("id", "myDiv"),
     );

Now, if I want to add some content into myDiv which contains HTML, the XElement automatically escapes this which, in my situation, is undesirable.

So if I have:

var elmnt = new XElement("div",
     new XAttribute("id", "myDiv"),
     "<span id='content'>hello world</span>"
     );

And then I render this into a Placeholder object using the following code:

myPlaceholder.Controls.Add(new System.Web.UI.WebControls.Literal { Text = elmnt.CreateNavigator().OuterXml });

When the page loads, the source reveals that the inner content inside elmnt has been escaped, and has the following format in the page's source:

&lt;span id='content'&gt;hello world&lt;/span&gt;

Given that the XML I'm compiling here is valid HTML, and the inner content is also valid HTML, how can I tell the XElement parent object to not escape the inner content? How can I leave it in its native format?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 var elmnt = new XElement("div",
   new XAttribute("id", "myDiv"),
   new XRaw("<span id='content'>hello world</span>")
 );


public class XRaw : XText
{
  public XRaw(string text):base(text){}
  public XRaw(XText text): base(text){}

  public override void WriteTo(System.Xml.XmlWriter writer)
  {
    writer.WriteRaw(this.Value);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...