这与以下问题相同:使用 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:
<field/>
但我需要的始终是开始和结束标记,即
But what I need is always opening and closing tag, i.e.
<field></field>
问题:怎么做?
添加空节点:
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 是 The Evil 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);
}
}
}
}
产生以下内容:
<?xml version="1.0" encoding="utf-8"?>
<RootElement>
<ChildElement ChildAttribute="AttrValue"></ChildElement>
</RootElement>
这篇关于您如何强制使用 Linq XML 关闭显式标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!