2

I currently have:

XNamespace xmlns = "XSDName";<br>
XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";<br>
XNamespace schemaloc = @"XSDName XSDName.xsd";
XDocument xdoc = new XDocument(
    new XElement("BaseReport",
    new XAttribute(xsi + "schemaLocation", schemaloc),
    new XAttribute(XNamespace.Xmlns+"ns1", xmlns),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi));

This gives me:

BaseReport xsi:schemaLocation="XSDName XSDName .xsd" xmlns:ns1="XSDName" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

How can I have BaseReport read ns1:BaseReport?

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
user2073374
  • 23
  • 1
  • 4
  • Can you add the assignment for the variables `xsi`, `schemaloc` and `xmlns` to your code sample? – Ryan Gates Feb 20 '13 at 18:22
  • After doing additional research, I don't believe that you can use a namespace in the root element. The namespace is defined as an attribute of the root element and would be undefined for the root itself. You can read more [here](http://stackoverflow.com/q/4985974/299327). – Ryan Gates Feb 20 '13 at 19:38
  • But, when I use something like XMLSpy to generate a sample xml from the XSD's it uses "ns1:BaseReport" as the header tag... – user2073374 Feb 20 '13 at 19:41
  • And it doesn't declare the `ns1` namespace at a higher level? Where does it declare this namespace? – Ryan Gates Feb 20 '13 at 19:42
  • The XMLSpy generator generates an xml with an xml header the same as what I'm looking to do with code, I just don't know how to get the "ns1:BaseReport" portion in code so that it validates properly. – user2073374 Feb 20 '13 at 19:56
  • I found an example of what you are talking about in [this question](http://stackoverflow.com/q/4406330/299327), but I am still trying to understand it. – Ryan Gates Feb 20 '13 at 20:25

1 Answers1

4

The below code will give you the output that you want. The key is adding the defined namespace before the name and letting .NET figure out the correct prefix.

XNamespace xmlns = "XSDName";
XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";
XNamespace schemaloc = @"XSDName XSDName.xsd";
XDocument xdoc = new XDocument(
    new XElement(xmlns + "BaseReport",
    new XAttribute(xsi + "schemaLocation", schemaloc),
    new XAttribute(XNamespace.Xmlns + "ns1", xmlns),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi)));
Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
  • Ah, yeah I got this from the previous link you sent +/- some fiddling. [Page didn't refresh, derp.] Thanks so much! – user2073374 Feb 21 '13 at 15:11