没有数据时强制XDocument.ToString()包含结束标记 [英] Forcing XDocument.ToString() to include the closing tag when there is no data

查看:31
本文介绍了没有数据时强制XDocument.ToString()包含结束标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的XDocument:

I have a XDocument that looks like this:

 XDocument outputDocument = new XDocument(
                new XElement("Document",
                    new XElement("Stuff")
                )
            );

当我打电话时

outputDocument.ToString()

输出到此:

<Document>
    <Stuff />
</Document>

但是我希望它看起来像这样:

But I want it to look like this:

<Document>
    <Stuff>
    </Stuff>
</Document>

我知道第一个是正确的,但是我必须以这种方式输出它.有什么建议吗?

I realize the first one is correct, but I am required to output it this way. Any suggestions?

推荐答案

将每个空XElementValue属性设置为专门的空字符串.

Set the Value property of each empty XElement specifically to an empty string.

    // Note: This will mutate the specified document.
    private static void ForceTags(XDocument document)
    {
        foreach (XElement childElement in
            from x in document.DescendantNodes().OfType<XElement>()
            where x.IsEmpty
            select x)
        {
            childElement.Value = string.Empty;
        }
    }

这篇关于没有数据时强制XDocument.ToString()包含结束标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆