不完整的XML属性

我是通过dataset.GetXML()方法从Dataset创建XML。 我想为它添加属性

XmlAttribute attr = xmlObj.CreateAttribute("xmlns:xsi"); attr.Value = "http://www.createattribute.com"; xmlObj.DocumentElement.Attributes.Append(attr); attr = xmlObj.CreateAttribute("xsi:schemaLocation"); attr.Value = "http://www.createattribute.com/schema.xsd"; xmlObj.DocumentElement.Attributes.Append(attr); xmlObj.DocumentElement.Attributes.Append(attr); 

但是当我打开XML文件时,我发现schemaLocation的属性中没有“xsi:”

   

我想要这个属性

  xsi:schemaLocation="http://www.createattribute.com/schema.xsd" 

这总是这样,或者我在这里遗漏了一些东西。 我很好奇是否有人可以帮助我,如果这可以解决或给我一些URL,我可以找到解决方案

谢谢

这里的关键是你需要告诉XmlWriter使用哪些命名空间,从那里它将应用正确的前缀。

在下面的代码中,SetAttribute方法中的第二个参数是为xmlns:xsi名称空间指定的名称空间uri。 这使得XmlWrite放入正确的前缀。

 XmlDocument xmlObj = new XmlDocument(); xmlObj.LoadXml(""); XmlElement e = xmlObj.DocumentElement; e.SetAttribute("xmlns:xsi", "http://www.createattribute.com"); e.SetAttribute("schemaLocation", "http://www.createattribute.com", "http://www.createattribute.com/schema.xsd"); 

使用原始问题的语法的类似代码是:

 XmlDocument xmlObj = new XmlDocument(); xmlObj.LoadXml(""); XmlAttribute attr = xmlObj.CreateAttribute("xmlns:xsi"); attr.Value = "http://www.createattribute.com"; xmlObj.DocumentElement.Attributes.Append(attr); attr = xmlObj.CreateAttribute("schemaLocation", "http://www.createattribute.com"); attr.Value = "http://www.createattribute.com/schema.xsd"; xmlObj.DocumentElement.Attributes.Append(attr); 

您需要单独指定前缀,而不是名称的一部分。 没有重载仅带有前缀和名称,因此您必须使用也占用命名空间的重载,并对命名空间使用null:

 attr = xmlObj.CreateAttribute("xsi", "schemaLocation", null);