Is there a way to add the string "xsi:type="SomeType" using XmlWriter class ?
My Element should look like this:
<Event xsi:type="SomeEvent" filename="c:\myFile.txt" ilepresence="Present">
I could not find a way to add an attribute "xsi:type" to an Element using XmlWriter. I ended up using XmlDocument instead and was able to achieve my goal.
This was my code for achieving the same:
XmlElement items = xmlDoc.CreateElement("Items");
xmlDoc.AppendChild(items);
xmlDoc.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
xmlDoc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlDoc.DocumentElement.SetAttribute("xmlns", "http://myCompany.com/v1");
Then later in the code, I did this:
XmlAttribute xsiType = xmlDoc.CreateAttribute("xsi", "type", "http://www.w3.org/2001/XMLSchema");
xsiType.Value = "MyAttributeValue";
Hope this helps someone.
Once you write the start of the element, you can use WriteAttributeString() to add an attribute to it. For example:
string xsins = "http://www.w3.org/2001/XMLSchema-instance";
// Make sure you add this namespace to the root element...
writer.WriteAttributeString(localName: "xsi", ns: xmlns,
value: xsins);
// Now you can reference that namespace in any child element
writer.WriteStartElement("Event");
writer.WriteAttributeString("type", xsins, "xsd:SomeEvent");
writer.WriteEndElement();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.