【问题标题】:XDocument create XElement with XML commentXDocument 使用 XML 注释创建 XElement
【发布时间】:2014-05-23 17:39:35
【问题描述】:

我一直在尝试像这样选择一些 XML cmets:

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

通过这个解决方案,我得到了文件的所有 xml 注释,但我只想选择那些 cmets 并用它创建 XElement:

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

有什么解决办法吗? :S

【问题讨论】:

  • 如何选择 to 标签中的内容转换成XElement

标签: c# xml linq-to-xml


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多