用<a> tag using C#.net</a>包装xml节点

时间:2011-03-10 04:11:50

标签: c# xmldocument

我正在尝试使用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添加到此问题中。

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

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变得更加烦人: - )

相关问题