首页 > 解决方案 > XmlDocument loping (foreach) reomving NameSpace "xmlns"

问题描述

嘿伙计们,我有 XML 文件,我正在使用 XDocument 在上面写,并使用下一个 void 删除命名空间

string path = Server.MapPath(xmlpath);
XDocument doc = XDocument.Load(path)
XElement root = new XElement("url");
foreach (var node in doc.Root.Descendants()
                           .Where(n => n.Name.NamespaceName == ""))
                {
                    node.Attributes("xmlns").Remove();
                    node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
                }

现在我改变了这个函数 100% 与 XDocument 一起工作

XDocument oldDoc = XDocument.Load(path);// the old doucument

XmlDocument newDoc = new XmlDocument();//the new document 

我需要一个函数,允许我从我的节点中进行 loping 和删除命名空间 xmlns,就像上面一样,非常感谢你们的时间,非常感谢阅读我的问题

标签: c#xmlasp.net-core

解决方案


你非常接近,只需要使用 返回a 的XMLDocument.CreateElement(string Name)重载,然后使用属性来设置你的XMLNode.InnerText

var mainRoot = doc.DocumentElement; //urlset element
var urlRoot = doc.CreateElement("url"); //create url element
var VidooTree = urlRoot.AppendChild(doc.CreateElement(a, ""));
urlRoot.AppendChild(doc.CreateElement("loc", "http:/domain/site.com"));
VidooTree.AppendChild(doc.CreateElement(b)).InnerText="imgur";
VidooTree.AppendChild(doc.CreateElement(c)).InnerText= "videoTitle";
VidooTree.AppendChild(doc.CreateElement("video:description")).InnerText= "videoDec";
VidooTree.AppendChild(doc.CreateElement(d)).InnerText= "VideoApi";
VidooTree.AppendChild(doc.CreateElement(m)).InnerText= "duration";
VidooTree.AppendChild(doc.CreateElement(nn)).InnerText= "2050-11-05T19:20:30+08:00";
VidooTree.AppendChild(doc.CreateElement(e)).InnerText= "watched";
VidooTree.AppendChild(doc.CreateElement(k)).InnerText= "date";
VidooTree.AppendChild(doc.CreateElement(f)).InnerText= "yes";
VidooTree.AppendChild(doc.CreateElement(g)).InnerText="No";
VidooTree.AppendChild(doc.CreateElement(h)).InnerText= "VideoKindName";
urlRoot.AppendChild(VidooTree);
mainRoot.AppendChild(urlRoot);

输出

<url xmlns="">
 <loc xmlns="http:/domain/site.com" />
  <video>
    <thumbnail_loc>imgur</thumbnail_loc>
    <title>videoTitle</title>
    <description>videoDec</description>
    <content_loc>VideoApi</content_loc>
    <duration>duration</duration>
    <expiration_date>2050-11-05T19:20:30+08:00</expiration_date>
    <view_count>watched</view_count>
    <publication_date>date</publication_date>
    <family_friendly>yes</family_friendly>
    <live>No</live>
    <category>VideoKindName</category>
  </video>
</url>

推荐阅读