gpt4 book ai didi

c# - 使用 Linq to XML 在节点之前插入 XComment

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:54 25 4
gpt4 key购买 nike

我需要在每个节点的正上方插入一个 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。

最佳答案

试试这个:-

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,如果不匹配,您可能会得到空引用异常,因此您必须在添加注释之前检查空值。

关于c# - 使用 Linq to XML 在节点之前插入 XComment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29072823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com