[英]Wrap xml node with <A> tag using C#.net
我試圖使用C#.net從Web服務返回所有圖像標簽周圍的href標簽。 我有以下代碼來獲取所有圖像
foreach (XmlNode xNode in xDoc.SelectNodes("Document/Content//img"))
{
// After I get the img I need to wrap a <a> tag around the image with an onclick attribute
}
有人可以幫我代碼嗎? 我無法將從Web服務返回的xml添加到此問題中。
這應該做的伎倆:
foreach (XmlElement el in xDoc.SelectNodes("//img")) {
// Replace image element with an 'a' element that wraps it
var aElement = xDoc.CreateElement("a");
aElement.SetAttribute("href", "http://example.com");
aElement.SetAttribute("onclick", "alert('Maple syrup!');");
aElement.AppendChild(el.Clone());
el.ParentNode.ReplaceChild(aElement, el);
}
請注意,我在循環中使用的類型是XmlElement
而不是XmlNode
(因為所有img
元素應該是......元素,這允許我們做更多的東西,而不僅僅是基礎XmlNode
類允許的)。
您可能還想查看LINQ-to-XML ,這使得創建XML變得不那么煩人了:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.