[英]Insert XComment before node using Linq to XML
I need to insert a xml comment XComment
right above each node. 我需要在每个节点的正上方插入一个xml注释XComment
。 It is the same as this question Using XPath to access comments a flat hierachy . 与此问题相同使用XPath访问注释平面层次结构 。 What would be the eqivalent of //comment()[following-sibling::*[1][self::attribute]]
in Linq? Linq中//comment()[following-sibling::*[1][self::attribute]]
的等价是什么?
A use case for me would be like this: 我的用例就像这样:
<root>
<node id="1">
<element>test</element>
</node>
<!-- comment here: TODO: check if ok -->
<node id="2">
<element>is this ok?</element>
</node>
</root>
Sorry, there seems to be a misunderstanding. 对不起,似乎有一种误解。 I have a xml file and need to add a XComment
after I select a node using Linq and lambda expression. 我有一个xml文件,需要在使用Linq和lambda表达式选择节点后添加XComment
。 That means I load a xml, select a node under root and add XComment. 这意味着我加载一个xml,在root下选择一个节点并添加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?")
)
)
);
I guess you are reading an existing file and want to add the comments there, so this should work for you: 我猜您正在阅读现有文件,并希望在那里添加评论,所以这应该适合您:
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"));
}
If you have to use LINQ and not XPath for some reason, use this: 如果由于某种原因必须使用LINQ而不是XPath,请使用:
var nodes = xdoc.Descendants().Where(n=>n.Name=="node");
foreach (var n in nodes)
{
n.AddBeforeSelf(new XComment("This is your comment"));
}
Try this:- 尝试这个:-
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");
Here, in the filter clause you need to pass the condition before which you wish to add your comments. 在这里,在filter子句中,您需要传递您希望添加注释的条件。 Please notice since I have used FirstOrDefault
, you may get null reference exception in case of no match, thus you'll have to check for nulls before adding the comments. 请注意,因为我使用了FirstOrDefault
,如果没有匹配,你可能会得到空引用异常,因此你必须在添加注释之前检查空值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.