c# - 将具有值的 XElement 转换为空元素(其中 XElement.IsEmpty = true)

标签 c# .net

我正在使用 C# .Net 3.5 并尝试将给定的 xml (XDocument) 转换为一个空的(其中 XElement.IsEmpty 为真)不包含文本值。我尝试将 XElement.Value 设置为 String.Empty 但这导致 <element><element>这不是我需要的。我需要它是 <element /> .有人可以建议如何在 .NET 中完成此操作。

下面是输入示例:

    <Envelope>
        <Body>
            <Person>
                <first>John</first>
                <last>Smith</last>
                <address>123</address>
            </Person>
        </Body>
    <Envelope>

预期输出:

    <Envelope>
        <Body>
            <Person>
                <first />
                <last />
                <address />
            </Person>
        </Body>
    <Envelope>

最佳答案

您可以使用 ReplaceWith()用空元素替换所需元素的函数:

var xml = @"<Envelope>
        <Body>
            <Person>
                <first>John</first>
                <last>Smith</last>
                <address>123</address>
            </Person>
        </Body>
    </Envelope>";
var doc = XDocument.Parse(xml);
foreach (XElement propertyOfPerson in doc.XPathSelectElements("/Envelope/Body/Person/*").ToList())
{
    propertyOfPerson.ReplaceWith(new XElement(propertyOfPerson.Name.LocalName));
}
Console.WriteLine(doc.ToString());

结果: enter image description here

关于c# - 将具有值的 XElement 转换为空元素(其中 XElement.IsEmpty = true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23036773/

相关文章:

c# - 下载时获取文件名

C# JSON 自定义序列化

C# 在枚举中使用数字

c# - 为什么 .net 语言的性能会有所不同?

c# - Expression.Call 跳过或接听

c# - 如何在gridview中绑定(bind)变量值?

c# - session 状态服务器与自定义 session 状态提供程序

.net - LINQ Join 运算符是否使用嵌套循环、合并或 HashSet 连接?

c# - C# 中 Substring 的意外行为

c# - PowerCollections 中 GetValueElseAdd 的 BCL 等价物是什么