我有一個這樣的 XML:
<root>
<parent1>Some random <child1>text </child1>here. And a random <child2>image </child2>here.</parent1>
</root>
并且想要這個:
<root>Some random <child1>text </child1>here. And a random <child2>image </child2>here.</root>
在我使用這個之前:
foreach (var p in doc.Descendants("parent1"))
p.ReplaceWith(p.Value);
結果是:
<root>Some random text here. And a random image here.</root>
但現在我必須保留子節點。
uj5u.com熱心網友回復:
創建一個XElement具有相同名稱的新root元素 ( ) 并包含其第一個元素 ( parent) 的節點。
const string Xml = @"
<root>
<parent1>Some random <child1>text </child1>here. And a random <child2>image </child2>here.</parent1>
</root>";
var xml = XElement.Parse(Xml);
var result = new XElement(
xml.Name,
xml.Elements().First().Nodes()
);
Console.WriteLine(result);
我更喜歡替換,然后用它的節點替換第一個元素。
請注意,這會影響原始xml XElement.
var first = xml.Elements().First();
first.ReplaceWith(first.Nodes());
Console.WriteLine(xml);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/411349.html
標籤:
