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 关闭显式标记?
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01