简体   繁体   English

使用System.Xml.Linq命名空间显式元素关闭标记

[英]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). 我使用(.NET 3.5 SP1)System.Xml.Linq命名空间来填充带有div标签的数据的html模板文档(然后将其保存到磁盘)。 Sometimes the div tags are empty and this seems to be a problem when it comes to HTML. 有时div标签是空的,这在HTML方面似乎是一个问题。 According to my research, the DIV tag is not self-closing. 根据我的研究,DIV标签不是自动关闭的。 Therefore, under Firefox at least, a <div /> is considered an opening div tag without a matching closing tag. 因此,至少在Firefox下, <div />被认为是一个没有匹配结束标记的开始div标签。

So, when I create new div elements by declaring: 所以,当我通过声明创建新的div元素时:

XElement divTag = new XElement("div"); 

How can I force the generated XML to be <div></div> instead of <div /> ? 如何强制生成的XML为<div></div>而不是<div />

I'm not sure why you'd end up with an empty DIV (seems a bit pointless!) But: 我不知道为什么你最终得到一个空的DIV(似乎有点无意义!)但是:

divTag.SetValue(string.Empty);

Should do it. 应该这样做。

With XElement divTag = new XElement("div", String.Empty); 使用XElement divTag = new XElement(“div”,String.Empty); you get the explicit closing tag 你得到明确的结束标记

I don't know the answer to your question using LINQ. 我不知道使用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. 但是在codeplex上有一个名为HTML Agility Pack的项目,它允许您创建和操作HTML文档,这与我们使用System.Xml命名空间类操作XML文档的方式非常相似。

I did this. 我这样做了 Working as expected. 按预期工作。

myXml = new XElement("script", new XAttribute("src", "value"));
myXml .Value = "";

Which gives below as result. 结果如下。

<script src = "value"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM