Question

I've tried looking this up on MSDN, W3Schools, and a number of other sites, and nobody seems to have the answer. Here's my problem:

I'm trying to generate a start element for an XML document. The specific element that I need to create is this:

<ns1:getRecordsResponse xmlns:ns1="http://someurl/schemas">

Based on the research I've done, I've been able to get the second half of that element properly generated using this code:

writer.WriteAttributeString("xmlns", "ns1", null, "http://someurl/schemas");

I can't get the first part to generate properly, though. I've tried using writer.StartElement("ns1", "getRecordsResponse"), that same line but the names reversed, I've tried adding null as a third argument in each of the three spots, and it never comes out right. I've also tried to use the WriteElementString method, but I must not be doing that correctly because it throws invalid operation exceptions:

writer.WriteElementString("ns1", "getCitationsResponse", "http://someurl/schemas", null);

How can I get the element written properly?

Was it helpful?

Solution

This seems to do what you want:

using System;
using System.Xml;

class Test
{
    public static void Main(string[] args)
    {
        using (var writer = XmlWriter.Create(Console.Out))
        {
            writer.WriteStartElement("ns1", "foo", "http://someurl/schemas");
            writer.WriteAttributeString("xmlns", "ns1", null, "http://someurl/schemas");
            writer.WriteEndElement();
        }
    }
}

Output (leaving out the XML declaration):

<ns1:foo xmlns:ns1="http://someurl/schemas" />

Looking at the documentation for that overload of WriteStartElement it should be clear why that works, as these are the parameters in order:

  • prefix
    Type: System.String
    The namespace prefix of the element.
  • localName
    Type: System.String
    The local name of the element.
  • ns
    Type: System.String
    The namespace URI to associate with the element.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top