How to add schemaLocation when using LxSerializer
Question asked by Scott Zrubek - 4/20/2021 at 6:08 PM
Answered
Some of the customers of our exported XML files requested that we add 
xsi:schemaLocation="http:aaa.org/bbb/ccc"
to the top level element.

I tried add the following to the root class that is exported:

        [XmlAttribute("schemaLocation", Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
        public string xsiSchemaLocation = @"http:aaa.org/bbb/ccc" 

to no avail.

I don't think using the NamespaceMap is appropriate and I see no other likely suspects within the LxWriterSettings

Any suggestions?

2 Replies

Reply to Thread
0
Liquid Support Replied
Employee Post Marked As Answer
You can do this using the UnprocessedAttributes collection...

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";;
string xml =
@"<Configuration>
  <A type='test'/>
  <B type='test2'/>
  <C type='test3'/>
</Configuration>";

var s = new LiquidTechnologies.XmlObjects.LxSerializer<ConfigurationElm>();
using (StringReader reader = new StringReader(xml))
{
    var o = s.Deserialize(reader);

    // add schema location attribute
    o.UnprocessedAttributes.Add(new XAttribute(xsi + "schemaLocation", "http://server/myschema.xsd";));

    using (StringWriter writer = new StringWriter())
    {
        s.Serialize(writer, o);
        Debug.Write(writer.ToString());
    }
}
Note: this requires that 'Unprocessed Handlers' is checked (this is checked by default)...


0
Scott Zrubek Replied
Thanks!

The key part being:

                    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";;
                    dto.UnprocessedAttributes.Add(new XAttribute(xsi + "schemaLocation", namespaceDict["schemaLocation"]));
                    var extendedStringWriter = new ExtendedStringWriter(writer.GetStringBuilder(), Encoding.UTF8);
                    serializer.Serialize(extendedStringWriter, dto, lxWriterSettings, spaceSystemXML);

Reply to Thread