如何使用c#.net CF 3.5中的XmlDocument向xml添加属性

我需要为元素“aaa”创建一个带有前缀“xx”的属性“abc”。 以下代码添加了前缀,但它还将namespaceUri添加到元素中。

要求输出:

   

我的代码:

  XmlNode node = doc.SelectSingleNode("//mybody"); XmlElement ele = doc.CreateElement("aaa"); XmlAttribute newAttribute = doc.CreateAttribute("xx","abc",namespace); newAttribute.Value = "ddd"; ele.Attributes.Append(newAttribute); node.InsertBefore(ele, node.LastChild); 

上面的代码生成:

    

期望的输出是

    

并且“xx”属性的声明应该在根节点中完成,如:

  

如何以deisred格式获取输出? 如果xml不是这种所需的格式,那么它就不能再被处理了..

有人可以帮忙吗?

谢谢,Vicky

我相信这只是直接在根节点上设置相关属性的问题。 这是一个示例程序:

 using System; using System.Globalization; using System.Xml; class Test { static void Main() { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("root"); string ns = "http://sample/namespace"; XmlAttribute nsAttribute = doc.CreateAttribute("xmlns", "xx", "http://www.w3.org/2000/xmlns/"); nsAttribute.Value = ns; root.Attributes.Append(nsAttribute); doc.AppendChild(root); XmlElement child = doc.CreateElement("child"); root.AppendChild(child); XmlAttribute newAttribute = doc.CreateAttribute("xx","abc", ns); newAttribute.Value = "ddd"; child.Attributes.Append(newAttribute); doc.Save(Console.Out); } } 

输出: