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

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

<?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节点,结果如下:

<?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#代码如下:

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",非常讨厌吧!

因为默认情况下,创建的Xml节点会自动判断其自身的NameSpace和父节点(比如url插入到urlset,自动判断url的Namespace和父节点的Namespace)是否一致,如果一致那么就不会再添加

因此解决方案是:

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");
结论:插入到哪个父节点,直接用红体字获取自身节点命名空间,然后插入即可

相关文章:

  • 2022-01-13
  • 2022-01-28
  • 2021-08-21
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
  • 2021-06-04
猜你喜欢
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2021-12-02
  • 2021-08-29
相关资源
相似解决方案