This code does the trick!
public void WriteXml(XmlWriter writer)
{
const string ns1 = "http://firstline.com/";
const string xsi = "http://www.w3.org/2001/XMLSchema-instance";
writer.WriteStartElement("myRoot", ns1);
writer.WriteAttributeString("SchemaVersion", "1.0");
writer.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", xsi);
writer.WriteAttributeString("xsi", "schemaLocation", xsi, ns1 + " schema1.xs");
writer.WriteStartElement("element1", ns1);
writer.WriteElementString("test1", ns1, "test value");
writer.WriteElementString("test2", ns1, "value 2");
writer.WriteEndElement();
writer.WriteEndElement();//to close classname that has root xml
}
Xml with multiple awesome namespaces!
<?xml version="1.0" encoding="utf-16"?>
<myClassNameWhereIXmlSerializableIsImplemented>
<myRoot SchemaVersion="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://firstline.com/ schema1.xs" xmlns="http://firstline.com/">
<element1>
<test1>test value</test1>
<test2>value 2</test2>
</element1>
</myRoot>
</myClassNameWhereIXmlSerializableIsImplemented>
There is something confusing about this line
writer.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", xsi);
if you give a random url instead of "http://www.w3.org/2000/xmlns/" , it will fail. The url that appear in xml is actually from "xsi" variable.
One more example to prove the point
writer.WriteAttributeString("xml", "base", "http://www.w3.org/XML/1998/namespace", base1);
where base1 = "<custom url>"
and if you want to output with a prefix like this <d:test1>somevalue<\d:test1> then writer.WriteElementString("d","test1", ns1, "somevalue"); if ns1 is not defined above then it will be added in xml output.
but for
<d:test1>
<blah>...
<\d:test1>
StartElement is needed writer.WriteStartElement("test1", ns1); to be closed when needed with writer.WriteEndElement();
oneshotobject?