我正在使用 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());
结果:
关于c# - 将具有值的 XElement 转换为空元素(其中 XElement.IsEmpty = true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23036773/