2014-05-23 83 views
1

我一直想選擇像這樣一些XML註釋:的XDocument與XML註釋創建的XElement

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

+0

什麼問題嗎? :S –

+0

如何選擇<! - START - >中的內容到標記以將其轉換爲XElement – C1rdec

回答

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>