您如何强制使用 Linq XML 关闭显式标记?

0

本文介绍了您如何强制使用 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 关闭显式标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14