0

I am creating an xml document from Sql Server data using C# and XElement and the client spec requires an attribute namespace xmlns in the main tag (case is the main tag). Here is the example from their spec:

<case techname="Client" count="4" xmlns="http://tempuri.org/NBAppSchema.xsd">

My problem is that I am getting an error in C# trying to output this 'case' tag's xmlns attribute with using a prefix. (error: The prefix '' cannot be redefined from '' to 'http://example.com/xmlns1' within the same start element tag.)

When I include a prefix, it generates the xml fine only the client tells me that when they try to load it, it errors out. Example with prefix:

<case techname="Client" count="4" xmlns:prfx="http://tempuri.org/NBAppSchema.xsd">

Code:

XNamespace ns = "http://tempuri.org/NBAppSchema.xsd";
XElement mainCaseTag = new XElement("case", new XAttribute("techname", "Univers"), new XAttribute("count", totalApplicationCount), new XAttribute(XNamespace.Xmlns + "prfx", ns));

I would like to output this attribute as the first example without the prefix. I have tried to research, but cannot find or understand how to output this xml file with a namespace without the prefix.

pnuts
  • 58,317
  • 11
  • 87
  • 139
kjsharks
  • 51
  • 3

1 Answers1

1

Try this:

XNamespace ns = "http://tempuri.org/NBAppSchema.xsd";      
var doc2 = new XDocument(
    new XElement(ns + "root",
        new XAttribute("attr1", "val1"), 
        new XElement(ns + "SubNode")));
Console.WriteLine(doc2.ToString());

And the demo with 2 options.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Tony
  • 7,345
  • 3
  • 26
  • 34
  • Hi Tony/John, great thank you. I think that option #2 is what I'm looking for only how do I add all my nodes and subnodes in this format. My setup is a little different in that I create a main element (case) adding subnodes to nodes and adding nodes to the main element case. At the end I XDocument xmlFile = new XDocument(caseTag) and then xmlFile.Save(fileName);....how can I accomplish this with the way you structured your option#2. Sorry I am new to XML and there are so many ways!! – kjsharks Dec 24 '13 at 15:02
  • Ok so I'm restructuring the way I build the xml by creating the XDocument doc = (new XDocument(new XElement(ns + "case", new XAttribute("techname", "Client"), new XElement("casename", caseName) etc.... Only now it is putting xmlns="" in each node...is there a way to not have this in each node? Thanks again! – kjsharks Dec 24 '13 at 15:33
  • ah...this helped http://stackoverflow.com/questions/61084/empty-namespace-using-linq-xml. put ns + before each node and then it does not include the blank ns = "" – kjsharks Dec 24 '13 at 16:29
  • ah ha, finally, all I had to do was put ns + in front of all nodes and it than will output the xmlns="http://tempuri.org/NBAppSchema.xsd" in the main node and it will ignore the empty xmlns="" in each node and subnode!! Nice... – kjsharks Dec 24 '13 at 16:59