【问题标题】:Insert XComment before node using Linq to XML使用 Linq to XML 在节点之前插入 XComment
【发布时间】:2015-03-16 17:28:33
【问题描述】:

我需要在每个节点正上方插入一个 xml 注释 XComment。和这个问题Using XPath to access comments a flat hierachy一样。在 Linq 中 //comment()[following-sibling::*[1][self::attribute]] 的等价物是什么?

对我来说一个用例是这样的:

<root>
 <node id="1">
  <element>test</element>
 </node>
 <!-- comment here: TODO: check if ok -->
 <node id="2">
  <element>is this ok?</element>
 </node>
</root>

抱歉,好像有误会。我有一个 xml 文件,需要在使用 Linq 和 lambda 表达式选择一个节点后添加一个 XComment。这意味着我加载一个 xml,在根目录下选择一个节点并添加 XComment。

【问题讨论】:

  • 您想要每个节点上方的 cmets,即 id 为 1,2?或高于任何特定节点?

标签: c# xml linq xpath


【解决方案1】:

试试这个:-

XDocument xdoc = XDocument.Load(@"YourXMl.xml");
xdoc.Descendants("node").FirstOrDefault(x => (string)x.Attribute("id") == "2")
                        .AddBeforeSelf(new XComment("comment here: TODO: check if ok"));
xdoc.Save(@"YourXML.xml");

在这里,您需要在过滤器子句中传递您希望在其之前添加 cmets 的条件。请注意,由于我使用了FirstOrDefault,如果不匹配,您可能会得到空引用异常,因此您必须在添加 cmets 之前检查空值。

【讨论】:

  • @sceiler - 很高兴它有帮助!快乐编码:)
【解决方案2】:
var doc = new XDocument(
            new XElement("root",
                new XElement("node",
                    new XComment("comment here: TODO: check if ok"),
                    new XElement("element", "is this ok?")
                    )
                )
            );

【讨论】:

    【解决方案3】:

    我猜你正在读取一个现有文件并想在其中添加 cmets,所以这应该适合你:

    var xdoc = XDocument.Load("//path/to/file.xml");
    var nodes = xdoc.XPathSelectElements("//node");
    foreach (var n in nodes)
    {
        n.AddBeforeSelf(new XComment("This is your comment"));
    }
    

    如果由于某种原因您必须使用 LINQ 而不是 XPath,请使用:

    var nodes = xdoc.Descendants().Where(n=>n.Name=="node");
    foreach (var n in nodes)
    {
        n.AddBeforeSelf(new XComment("This is your comment"));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      相关资源
      最近更新 更多