移除“xmlns”命名空间

用XmlDocument建立一个文档,或者插入一个节点,默认会生成xmlns(命名空间)特性。url

假定有一个xml文档以下结构:spa

<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://www.myWebSite.com/</loc>
  </url>
  <url>
    <loc>http://www.myWebSite.com/MGID_17</loc>
  </url>
  <url>
    <loc>http://www.myWebSite.com/MGID_18</loc>
  </url>
</urlset>

如今要在urlset插入一个url节点,结果以下:code

<?xml version="1.0" encoding="UTF-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
…………………………
  <url>
    <loc>New Value Here</loc>
  </url>
</urlset>

C#代码以下:xml

XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");
            XmlElement newEle = doc.CreateElement("url");
            XmlElement subEle = doc.CreateElement("loc");
            subEle.InnerText = "New Value Here";
            newEle.AppendChild(subEle);
            doc.DocumentElement.AppendChild(newEle);
            doc.Save("d:\\try.xml");

结果会在url节点加上"xmlns",很是讨厌吧!blog

由于默认状况下,建立的Xml节点会自动判断其自身的NameSpace和父节点(好比url插入到urlset,自动判断url的Namespace和父节点的Namespace)是否一致,若是一致那么就不会再添加文档

所以解决方案是:it

XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");
            XmlElement newEle = doc.CreateElement("url",doc.DocumentElement.NamespaceURI);
            XmlElement subEle = doc.CreateElement("loc",newEle.NamespaceURI);
            subEle.InnerText = "textboxValue";
            newEle.AppendChild(subEle);
            doc.DocumentElement.AppendChild(newEle);
            doc.Save("d:\\try.xml");
结论:插入到哪一个父节点,直接用红体字获取自身节点命名空间,而后插入便可
相关文章
相关标签/搜索