删除 Xml 节点的属性 c#

Delete Attribute of Xml node c#

我有一个这样的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ua="http://opcfoundation.org/UA/2008/02/Types.xsd" xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd">
  <ServerConfiguration>
    <SecurityPolicies>
      <ServerSecurityPolicy>
        <SecurityMode>None_1</SecurityMode>
      </ServerSecurityPolicy>
    </SecurityPolicies>
  </ServerConfiguration>
</ApplicationConfiguration>

我想要的是通过代码添加更多名为ServerSecurityPolicy的节点。 然后我使用这个代码:

            string docaddress = "D:\abc.xml";
            XDocument doc = XDocument.Load(docaddress);
            var root = doc.Root;
            var these = root.Descendants().Where(p => p.Name.LocalName == "SecurityPolicies");
            XElement addelement = new XElement("ServerSecurityPolicy");
            addelement.Add(new XElement("SecurityMode", "None_1"));           
            foreach (var elem in these)
            {
                elem.Add(addelement);
            }
            doc.Save(docaddress);

确实可以,但是新添加的节点是这样的:

      <ServerSecurityPolicy xmlns="">
        <SecurityMode>None_1</SecurityMode>
      </ServerSecurityPolicy>

我不想要属性“xmlns”,然后我尝试通过这样的方式删除它:

            var these2 = root.Descendants().Where(p => p.Name.LocalName == "ServerSecurityPolicy");
            foreach (var elem in these2)
            {
                    label2.Text += elem.Attribute("xmlns").Name.LocalName;
                    elem.Attribute("xmlns").Remove();
            }

label2.Text 显示“xmlnsxmlnsxmlsn...”,因此我认为 elem.Attribute(“xmlns”) 已指向我要删除的属性,但 Remove() 不起作用. 你能给我一些删除属性或添加没有属性的节点的方法吗?
谢谢

您获得空属性(xmlns="" 所指)的原因是您的文档的根节点属于命名空间 xsi。当您添加没有名称空间的节点时 - 正如您在示例中所做的那样 - 您实际上并未将其绑定到 xsi 名称空间。

要使您的节点成为根命名空间的一部分,请替换

new XElement("ServerSecurityPolicy")

new XElement("ServerSecurityPolicy",
              new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"))

问题是您要创建的元素实际上在 http://opcfoundation.org/UA/SDK/Configuration.xsd 命名空间中,这是文档的默认命名空间,因为根元素的这一部分:

xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd"

您可以轻松地在该命名空间中创建元素:

XNamespace configNs = "http://opcfoundation.org/UA/SDK/Configuration.xsd";
var these = root.Descendants(configNs + "ServerSecurityPolicy");

当您将 that 添加到您的文档时,您会发现它不会添加 xmlns="" 部分,该部分存在是因为您添加的元素没有命名空间。

我还建议也使用命名空间来查找元素:

XNamespace configNs = "http://opcfoundation.org/UA/SDK/Configuration.xsd";
var these = root.Descendants(configNs + "SecurityPolicies");

在我看来,这比仅使用本地名称要简洁得多。