C#创建有前缀命名空间的元素和属性
2017年1月27日要求创建如
XmlDocument docuemnt = new XmlDocument();
      XmlElement output = docuemnt.CreateElement(“Output”);
      XmlElement row = docuemnt.CreateElement(“Row”);
      row.SetAttribute(“nil”, “http://www.w3.org/2001/XMLSchema”, “true”);
      output.AppendChild(row);
      docuemnt.AppendChild(output);
      XmlWriter writer = XmlWriter.Create(Console.Out);
      docuemnt.WriteTo(writer);
      writer.Flush();
      Console.ReadKey();
创建的XML形如
缺点是nil的前缀不是自定义的。我需要前缀是xs。
XmlDocument docuemnt = new XmlDocument();
      XmlElement output = docuemnt.CreateElement(“Output”);
      XmlElement row = docuemnt.CreateElement(“Row”);
      XmlAttribute nil = docuemnt.CreateAttribute(“xs”, “nil”, “http://www.w3.org/2001/XMLSchema”);
      nil.Value = “true”;
      row.SetAttributeNode(nil);
      output.AppendChild(row);
      docuemnt.AppendChild(output);
      XmlWriter writer = XmlWriter.Create(Console.Out,new XmlWriterSettings { Indent=true});
      docuemnt.WriteTo(writer);
      writer.Flush();
      Console.ReadKey();
创建的XML形如
可是我想把 xmlns:xs=”http://www.w3.org/2001/XMLSchema”移动到Output元素。
方法是直接用SetAttribute方法写出XML命名空间。我本来以为会有专门的方法,或使用XmlNamespace类。
 XmlDocument docuemnt = new XmlDocument();
      XmlElement output = docuemnt.CreateElement(“Output”);
      output.SetAttribute(“xmlns:xs”, “http://www.w3.org/2001/XMLSchema”);
      XmlElement row = docuemnt.CreateElement(“Row”);
      XmlAttribute nil = docuemnt.CreateAttribute(“xs”, “nil”, “http://www.w3.org/2001/XMLSchema”);
      nil.Value = “true”;
      row.SetAttributeNode(nil);
      //row.SetAttribute(“nil”, “http://www.w3.org/2001/XMLSchema”, “true”);
      output.AppendChild(row);
      docuemnt.AppendChild(output);
      XmlWriter writer = XmlWriter.Create(Console.Out,new XmlWriterSettings { Indent=true});
      docuemnt.WriteTo(writer);
      writer.Flush();
      Console.ReadKey();