[英]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.