1

I'm trying to write a XML-document programatically.

I need to add <xsd:schema> tag to my document.

Currently I have:

var xmlDoc = new XmlDocument();

var root = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(root);

var xsdSchemaElement = xmlDoc.CreateElement("schema");
xsdSchemaElement.Prefix = "xsd";
xsdSchemaElement.SetAttribute("id", "root");

root.AppendChild(xsdSchemaElement);

However, this renders to:

<root>
  <schema id="root" />
</root>

How do I get the tag to be <xsd:schema>?

Already tried var xsdSchemaElement = xmlDoc.CreateElement("xsd:schema"); which simply ignores the xsd:.

Edit #1

Added method

private static XmlSchema GetTheSchema(XmlDocument xmlDoc)
{
    var schema = new XmlSchema();
    schema.TargetNamespace = "xsd";
    return schema;
}

which is called like xmlDoc.Schemas.Add(GetTheSchema(xmlDoc)); but does not generate anything in my target XML.

KingKerosin
  • 3,639
  • 4
  • 38
  • 77
  • The XmlDocument has a Property called Schemas. Have you tried adding your schema definition there? – Oliver Ulm Apr 14 '16 at 07:44
  • Using `xmlDoc.Schemas.Add(GetMySchema(xmlDoc))` is not throwing any exceptions, but also not writing any xml to my target-file. Any good tutorials on how to use `XmlSchema` you know about? – KingKerosin Apr 14 '16 at 07:54
  • @KingKerosin are you able to use LINQ-to-XML instead of `XmlDocument`? – har07 Apr 14 '16 at 08:10
  • @har07 Yes. Just read that starting with `XDocument` is way better than `XmlDocument`. Any good tutorials on that? – KingKerosin Apr 14 '16 at 08:12
  • @KingKerosin I don't have any specific tutorials to recommend. Here are some examples that you may learn from : [MSDN: XDocument Class Overview](https://msdn.microsoft.com/en-us/library/bb387063.aspx), [XML file creation Using XDocument in C#](http://stackoverflow.com/questions/2948255/xml-file-creation-using-xdocument-in-c-sharp) – har07 Apr 14 '16 at 08:57

1 Answers1

0

Using LINQ-to-XML, you can nest XElements and XAttributess in a certain hierarchy to construct an XML document. As for namespace prefix, you can use XNamespace.

Notice that every namespace prefix, such as xsd in your case, has to be declared before it is used, something like xmlns:xsd = "http://www.w3.org/2001/XMLSchema".

XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
var doc = 
    new XDocument(
        //root element 
        new XElement("root",
            //namespace prefix declaration
            new XAttribute(XNamespace.Xmlns+"xsd", xsd.ToString()),
            //child element xsd:schema
            new XElement(xsd + "schema",
                //attribute id
                new XAttribute("id", "root"))));
Console.WriteLine(doc.ToString());

output :

<root xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:schema id="root" />
</root>
har07
  • 88,338
  • 12
  • 84
  • 137