0

I'm using XMLDocument to create a XML file, but when i set an attribute to an element called "xsi:type" in the .xml generated file this attribute is changed to just "type".

This is the output that i'm expecting:

<ODX xsi:type="VALUE" />

This is my code

using System.Xml;
        public static void xml_test()
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            XmlElement ODX = doc.CreateElement("ODX");
            ODX.SetAttribute("xsi:type", "VALUE");
            doc.AppendChild(ODX);
            doc.Save("C:\\Users\\dev\\Pictures\\DocParser\\DocParser\\xml_question_test.xml");
        }

This is content of the xml_question_test.xml output file that i get,:

<ODX type="VALUE" />

Notice how change the name of the attribute from "xsi:type" to "type", i tried to set the name of the attribute as literal with @ before the string but it didn't work... i haven't found anything useful...

  • You need to add a definition for the `xsi:` namespace prefix. To do so see [this answer](https://stackoverflow.com/a/2920162/3744182) to [How to add xmlnamespace to a xmldocument](https://stackoverflow.com/q/2920142/3744182). – dbc Jun 03 '20 at 06:22
  • The xsi:type comes from an inherited class where serialization would have [XmlInclude("VALUE")] – jdweng Jun 03 '20 at 09:33

1 Answers1

1

Since you are adding xs, you need to specify the namespace which it represents.

public static void xml_test()
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        XmlElement ODX = doc.CreateElement("ODX");
        var attr = doc.CreateAttribute("xs:type", "http://www.w3.org/2001/XMLSchema");
        attr.Value = "VALUE";
        ODX.Attributes.Append(attr);
        doc.AppendChild(ODX);
        doc.Save("C:\\xml_question_test.xml");
    }

You can read more here about XML namespaces: https://www.w3schools.com/xml/xml_namespaces.asp

shtrule
  • 658
  • 10
  • 23
  • The output from your example is this : Is there a way just to show "xsi:type=VALUE"? – Christopher Martinez Jun 03 '20 at 15:01
  • 1
    @ChristopherMartinez - no, that is not well-formed XML so `XmlDocument` won't create it. The prefix `xsi:` is just a lookup to a namespace that must be defined within the scope of the element. If the prefix isn't defined, the XML is malformed. See e.g. https://www.w3schools.com/xml/xml_namespaces.asp: *When using prefixes in XML, a **namespace** for the prefix must be defined.* Also, you can always upload your desired XML to an online validator such as https://www.xmlvalidation.com/ to make sure it is well-formed. – dbc Jun 03 '20 at 15:25