How do you force explicit tag closing with Linq XML?(您如何强制使用 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:
<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 关闭显式标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您如何强制使用 Linq XML 关闭显式标记?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01