简体   繁体   中英

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" />

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);

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?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM