Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit Element Closing Tags with System.Xml.Linq Namespace

I am using the (.NET 3.5 SP1) System.Xml.Linq namespace to populate an html template document with div tags of data (and then save it to disk). Sometimes the div tags are empty and this seems to be a problem when it comes to HTML. According to my research, the DIV tag is not self-closing. Therefore, under Firefox at least, a <div /> is considered an opening div tag without a matching closing tag.

So, when I create new div elements by declaring:

XElement divTag = new XElement("div"); 

How can I force the generated XML to be <div></div> instead of <div /> ?

like image 820
Matthew Ruston Avatar asked Jan 20 '09 19:01

Matthew Ruston


People also ask

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .

What is XName in XML?

As with XML, an XName can be in a namespace, or it can be in no namespace. For C#, the recommended approach for creating an XName in a namespace is to declare the XNamespace object, then use the override of the addition operator.

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.

What is LINQ to XML?

LINQ to XML is an XML programming interface. LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.


3 Answers

I'm not sure why you'd end up with an empty DIV (seems a bit pointless!) But:

divTag.SetValue(string.Empty);

Should do it.

like image 166
Steven Robbins Avatar answered Oct 23 '22 17:10

Steven Robbins


With XElement divTag = new XElement("div", String.Empty); you get the explicit closing tag

like image 2
Daniele Armanasco Avatar answered Oct 23 '22 18:10

Daniele Armanasco


I don't know the answer to your question using LINQ. But there is a project called HTML Agility Pack on codeplex that allows you to create and manipulate HTML documents much similar to the way we can manipulate XML document using System.Xml namespace classes.

like image 1
red.clover Avatar answered Oct 23 '22 16:10

red.clover