Search code examples
c#xmlnamespacesxelementxattribute

Generate xml attributes


I have to create an xml file, that contains an element with attributes like:

 <element 
     xsi:schemaLocation="http://test.xsd" 
     xmlns="http://test2" 
     xmlns:xsi=http://test3>

I tried:

 XNamespace ns = "xsi";            
 var root = new XElement("element",
                       new XAttribute(ns + "schemaLocation", "http://test.xsd"), // (I)
                       new XAttribute(XNamespace.Xmlns, "http://test2"),         // (II)
                       new XAttribute(XNamespace.Xmlns + "xsi", "http://test3"), // (III)

But the only thing that is generated fine is (III):

 xmlns:xsi=http://test3

(I) is generated like:

 p1:schemaLocation="http://test.xsd" xmlns:p1="xsi"

and (II) is not generated because the line doesn't compile.

Any idea on how I could generate these attributes?

Thank you, L

EDIT - also found it here: Creating XML with namespaces and schemas from an XElement


Solution

  • const string ns = "http://test2";
    const string si = "http://test3";
    const string schema_location = "http://test.xsd";
    
    XNamespace xns = ns;
    XNamespace sinsp = si;
    
         XElement xe = new XElement(xns + "element",
               new XAttribute(XNamespace.Xmlns + "xsi", si),
               new XAttribute(sinsp+ "schemaLocation", schema_location),
               new XElement(xns + "sometag", "somecontent")
            );
    
         return xe;