你如何强制使用LINQ XML标记明确结束? [英] How do you force explicit tag closing with Linq XML?
问题描述
这是同样的问题:
外在因素结束标记与System.Xml.Linq的命名空间
但我使用.NET 4.0和答案不工作了。
but I use Net 4.0 and the answers do not work anymore.
问题是我救的标签,没有价值观真的,我的输出XML是这样的:
The problem is I save tags with no values really, and my output XML looks like this:
<现场/>
但我需要的是始终在打开和关闭标签,即
But what I need is always opening and closing tag, i.e.
<场>< /场>
问:如何办呢?
添加空节点:
if (field_xml == null) // always true, because I create the file for the first time
{
field_xml = new XElement(XMLKeys.field,String.Empty);
table_xml.Add(field_xml);
}
field_xml.SetAttributeValue(XMLKeys.name, field_info.Name);
// ... setting some other attributes of this node
和之后,保存XML:
var writer = new FullEndingXmlTextWriter(parameters.OutputFilename, Encoding.UTF8);
root_xml.Save(writer);
FullEndingXmlTextWriter是专业类的邪恶Greebo指出,(它应该迫使明确的结束标记)
FullEndingXmlTextWriter is the specialized class which The Evil Greebo pointed out (it is supposed to force explicit closing tag).
推荐答案
我无法重现你的错误。这将按预期在这两个4.0和3.5 NETFX:
I can't reproduce your error. This works as expected in both 4.0 and 3.5 netFX:
namespace ExplicitXmlClosingTags
{
using System.Xml;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
const string ElementRoot = "RootElement";
const string ElementChild = "ChildElement";
const string AttributeChild = "ChildAttribute";
XDocument xDoc = new XDocument();
XElement root = new XElement(ElementRoot);
XElement child = new XElement(ElementChild, string.Empty);
root.Add(child);
child.SetAttributeValue(AttributeChild, "AttrValue");
xDoc.Add(root);
XmlWriterSettings xws = new XmlWriterSettings();
xws.Indent = true;
using (XmlWriter xw = XmlWriter.Create("out.xml", xws))
{
xDoc.Save(xw);
}
}
}
}
生产以下内容:
producing following content:
<?xml version="1.0" encoding="utf-8"?>
<RootElement>
<ChildElement ChildAttribute="AttrValue"></ChildElement>
</RootElement>
这篇关于你如何强制使用LINQ XML标记明确结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!