使用 Linq 在节点前插入 XComment 到 XML

Insert XComment before node using Linq to XML

我需要在每个节点的正上方插入一个 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 文件,需要在 select 使用 Linq 和 lambda 表达式的节点后添加一个 XComment。这意味着我在 root 下加载一个 xml, select 节点并添加 XComment.

var doc = new XDocument(
            new XElement("root",
                new XElement("node",
                    new XComment("comment here: TODO: check if ok"),
                    new XElement("element", "is this ok?")
                    )
                )
            );

我猜您正在阅读现有文件并想在其中添加注释,所以这应该适合您:

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"));
}

试试这个:-

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");

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