XDocument使用XML注释创建XElement

时间:2014-05-23 17:39:36

标签: c# xml linq-to-xml

我一直在尝试选择一些XML评论:

XDocument doc = XDocument.Load(args[0]);    
var comments = from node in doc.Elements().DescendantNodesAndSelf()
                            where node.NodeType == XmlNodeType.Comment
                            select node as XComment;

使用此解决方案,我获取了该文件的所有xml注释,但我想只选择那些注释并使用它创建XElement:

<Connections>
     ...
    <!-- START Individual Account Authentication -->
    <!--<authentication mode="None"/>
    <roleManager enabled="false"/>
    <profile enabled="false"/>-->
    <!-- END Individual Account Authentication -->
     ...
</Connections>

任何解决方案? :S

1 个答案:

答案 0 :(得分:1)

以下是一个示例:

        XDocument doc = XDocument.Load("input.xml");
        foreach (XComment start in doc.DescendantNodes().OfType<XComment>().Where(c => c.Value.StartsWith(" START")).ToList())
        {
            XComment end = start.NodesAfterSelf().OfType<XComment>().FirstOrDefault(c => c.Value.StartsWith(" END"));
            if (end != null)
            {
                foreach (XComment comment in end.NodesBeforeSelf().OfType<XComment>().Intersect(start.NodesAfterSelf().OfType<XComment>()).ToList())
                {
                    comment.ReplaceWith(XElement.Parse("<dummy>" + comment.Value + "</dummy>").Nodes());
                }
                // if wanted/needed
                start.Remove();
                end.Remove();
            }
        }
        doc.Save("output.xml");

那给了我

<Connections>
  ...
  <authentication mode="None" /><roleManager enabled="false" /><profile enabled="false" />
  ...
</Connections>