开发者

Replace XComment with its Contents

Within a valid XML file, I have the following section:

<PropertyGroup>
  <WorkingDir>C:\SomeFolder\</WorkingDir>
</PropertyGroup>
<ItemGroup>
  <Files Include="$(WorkingDir)**\*.txt" />
  <!--<Files Include="$(WorkingDir)**\*.log" />-->
  <Files Include="$(WorkingDir)**\*.bat" />
  <!--<Files Include="$(WorkingDir)**\*.ps1" />
  <Files Include="$(WorkingDir)**\*.psm" />-->
  <Files Include="$(WorkingDir)**\*.cmd" />
</ItemGroup>

I load it using XDocument, and can then retrieve the list of comments by using XComment - but assume I only want the first one:

var xComment = (doc.Elements().DescendantNodes().OfType<XComment>().First();

I now want to replace this comment with its actual content:

xComment.ReplaceWith(xComment.Value);

However, this is what I get as output:

<PropertyGroup>
  <WorkingDir>C:\SomeFolder\</WorkingDir>
</PropertyGroup>
<ItemGroup>
  <Files Include="$(WorkingDir)**\*.txt" />
  &lt;Files Include="$(WorkingDir)**\*.log" /&gt;
  <Files Include="$(WorkingDir)**\*.bat" />
  <!--<Files Include="$(WorkingDir)**\*.ps1" />
  <Files Include="$(WorkingDir)**\*.psm" />-->
  <Files Include="$(WorkingDir)**\*.cmd" />
</ItemGroup>

If I output the contents of xComment.Value separately (using Console.WriteLine(), for example), I get <Files Include="$(WorkingDir)**\*.log" /> - so what happens to the angle brackets when I use XNode.Repla开发者_如何学运维ceWith()? How do ensure that the character formatting is preserved?


Well you need to parse the XML in the comment first i.e. xComment.ReplaceWith(XElement.Parse(xComment.Value)). That should work as long as the comment contains the markup of a single element node, as is the case for the first comment in your sample. In a more general case (i.e. when the comment contains markup for more than one element or other for other nodes) you need xComment.ReplaceWith(XElement.Parse("<dummy>" + xComment.Value + "</dummy>").Nodes()).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜