<?xml version="1.0" encoding="utf-8" ?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>http://www.example.com/sitemap1.xml.gz</loc>
        <lastmod>2004-10-01T18:23:17+00:00</lastmod>
    </sitemap>
    <sitemap>
        <loc>http://www.example.com/sitemap2.xml.gz</loc>
        <lastmod>2005-01-01</lastmod>
    </sitemap>
</sitemapindex>
public static void XmlInsertElement(string xmlPath, string MainNode, string Element, string Content)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            objXmlDoc.Load(xmlPath);
            XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
            XmlElement objElement = objXmlDoc.CreateElement(Element);
            objElement.InnerText = Content;
            objNode.AppendChild(objElement);
            objXmlDoc.Save(xmlPath);
        }改进XmlInsertElement方法增加删除,修改功能。 删除会直接删除sitemap节点,此节点没有属性,只能根据sitemap的子节点进行删除.修改节点值只能根据节点原有值修改。
求源码,和XmlInsertElement一样的方法。谢谢~和这个问题一起的 增删改

解决方案 »

  1.   

    Linq To Xml更新、删除
      

  2.   

    建议给XmlNode类型添加一些扩展方法,我随便写一个:
    public static class XmlHelper
    {
    public static XmlNode AppendChildX(this XmlNode node, string name, string innerXml)
    {
    XmlElement element = node.OwnerDocument.CreateElement(name);
    element.InnerXml = innerXml;
    node.AppendChild(element);
    return element;
    }
    }
    调用:
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(Server.MapPath("~/test.xml"));
    XmlNode sitemap = xmlDoc.DocumentElement.AppendChildX("sitemap", "");
    sitemap.AppendChildX("loc", "www.baidu.com");
    sitemap.AppendChildX("lastmod", "12345678");
    xmlDoc.Save(Server.MapPath("~/test.xml"));
      

  3.   

    再增加一个设置属性的扩展方法,随便写的:
    public static class XmlHelper
    {
    public static XmlNode AppendChildX(this XmlNode node, string name, string innerXml)
    {
    XmlElement element = node.OwnerDocument.CreateElement(name);
    element.InnerXml = innerXml;
    node.AppendChild(element);
    return element;
    }
    public static XmlElement SetAttributesX(this XmlNode node, params string[] values)
    {
    XmlElement element = node as XmlElement;
    for (int i = 0; i < values.Length / 2; i++)
    element.SetAttribute(values[i * 2].TrimStart('@'), values[i * 2 + 1]);
    return element;
    }
    }
    调用:
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(Server.MapPath("~/test.xml"));
    XmlNode sitemap = xmlDoc.DocumentElement.AppendChildX("sitemap", "");
    sitemap.AppendChildX("loc", "www.baidu.com").SetAttributesX("@id", "123", "@name", "Tim");
    sitemap.AppendChildX("lastmod", "12345678").SetAttributesX("@year", "2005");
    xmlDoc.Save(Server.MapPath("~/test.xml"));
      

  4.   

    说白了,这个xml就是站点地图用的 SiteMap.没有属性,而且每个二级节点和其中的子节点内容是一样的,所以要删除、更新只能通过节点内容修改、删除。 
    这样要怎么实现,求封装方法。