Incomplete XML attribute

ぐ巨炮叔叔 提交于 2019-12-31 03:03:31

问题


I am creating XML out of Dataset by dataset.GetXML() method. I want to add attributes to it

            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);

But when I open the XML file, I found "xsi:" was not there in the attribute for schemaLocation

           <root xmlns="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:xsi="http://www.createattribute.com"     
           schemaLocation="http://www.createattribute.com/schema.xsd">

I want the attribute like

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

Is this always like this, or i m missing something here. I am curious if anyone could help me if this could be resolved or give me some URL when I can find the solution for this

Thanks


回答1:


The key here is that you need to tell the XmlWriter what namespaces to use and from there it will apply the correct prefixes.

In the code below the second parameter in the SetAttribute method is the namespace uri specified for xmlns:xsi namespace. This lets the XmlWrite put in the right prefix.

XmlDocument xmlObj = new XmlDocument();
xmlObj.LoadXml("<root></root>");

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");

Similar code using the syntax from your original question is:

XmlDocument xmlObj = new XmlDocument();
xmlObj.LoadXml("<root></root>");

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); 



回答2:


You need to specify the prefix separately, not as part of the name. There is no overload that takes just a prefix and the name, so you have to use the overload that also takes a namespace, and use null for the namespace:

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


来源:https://stackoverflow.com/questions/1837399/incomplete-xml-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!