[英]Insert XComment before node using Linq to XML
我需要在每个节点的正上方插入一个xml注释XComment
。 与此问题相同使用XPath访问注释平面层次结构 。 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,在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?")
)
)
);
我猜您正在阅读现有文件,并希望在那里添加评论,所以这应该适合您:
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");
在这里,在filter子句中,您需要传递您希望添加注释的条件。 请注意,因为我使用了FirstOrDefault
,如果没有匹配,你可能会得到空引用异常,因此你必须在添加注释之前检查空值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.