Developer
Developer

Reputation: 8636

How to add Schema location and XSI dynamically to an XML file

Hi all i am creating an application to generate an XML file dynamically. In this i would like to add schemalocation and XSI to the XML Root how can i do this. I would like to add the following

xmlns="http://www.irs.gov/efile"

xsi:SchemaLocation="http://www.irs.goc/efile ReturnData941.xsd"

and

xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance"

This is my sample XML code that was generated dynamically

XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

doc.AppendChild(docNode);

XmlNode returnData = doc.CreateElement("ReturnData");
XmlAttribute documnetCount = doc.CreateAttribute("documentCount"); // after this i would like to add that schema
returnData.Attributes.Append(documnetCount);

So that i should get my XML as follows

<?xml version="1.0" encoding="UTF-8"?>
<ReturnData documentCount=""  xsi:SchemaLocation="http://www.irs.goc/efile ReturnData941.xsd" xmlns="http://www.irs.gov/efile" xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" />

Upvotes: 1

Views: 6500

Answers (2)

Michael Kay
Michael Kay

Reputation: 163352

I wonder if this is the best way of approaching things? Many validation APIs allow you to specify the schema location and instance document location independently, and that's likely to be more efficient than storing the schema location within the instance.

Generally I'm sceptical about xsi:schemaLocation anyway. If you're validating the instance, that's often because you don't trust it, and if you don't trust it, why should you trust its xsi:schemaLocation?

Upvotes: 0

shenhengbin
shenhengbin

Reputation: 4294

I think you just need add a attribute like

        XmlAttribute attr = doc.CreateAttribute("xsi", "schemaLocation", " ");
        attr.Value = "http://www.irs.goc/efile ReturnData941.xsd";
        returnData.Attributes.Append(attr);

Upvotes: 3

Related Questions