Funky
Funky

Reputation: 13602

Adding an attribute using XmlWriter

I am trying to add the following attribute to a node using an XmlWriter but nothing seems to work, does anyone have any ideas?

<news:news>

I am trying to achieve the following:

 <url>
    <loc>http://www.example.org/business/article55.html</loc>
    <news:news>
      <news:publication>
        <news:name>The Example Times</news:name>
        <news:language>en</news:language>
      </news:publication>
      <news:access>Subscription</news:access>
      <news:genres>PressRelease, Blog</news:genres>
      <news:publication_date>2008-12-23</news:publication_date>
      <news:title>Companies A, B in Merger Talks</news:title>
      <news:keywords>business, merger, acquisition, A, B</news:keywords>
      <news:stock_tickers>NASDAQ:A, NASDAQ:B</news:stock_tickers>
    </news:news>
  </url>

Thanks

Upvotes: 0

Views: 4254

Answers (2)

Tallek
Tallek

Reputation: 1575

Take a look at the following link for how to handle namespaces with the XmlWriter

Namespace Handling in the XmlWriter

You can manually write out the namespace declaration using the WriteAttributeString method, and then use the WriteStartElement(String, String) overload to associate future elements with that namespace, like so

writer.WriteStartElement("root");
writer.WriteAttributeString("xmlns", "x", null, "urn:1");
writer.WriteStartElement("item", "urn:1");
writer.WriteEndElement();
writer.WriteStartElement("item", "urn:1");
writer.WriteEndElement();
writer.WriteEndElement();

Upvotes: 1

Denis
Denis

Reputation: 6082

    using System;
    using System.Xml;

    class Program
    {
        static void Main(string[] args)
        {
            XmlWriter writer = new XmlTextWriter(Console.Out);
            writer.WriteStartElement("root");
            writer.WriteAttributeString("news", "http://www.stackoverflow.com");
            writer.WriteStartElement("news:news");
            writer.WriteStartElement("news:publication");
            writer.WriteElementString("news:name", "The Example Times");
            writer.WriteElementString("news:language", "en");
            // etc
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();
            Console.ReadKey(true);
        }
    }

Upvotes: 0

Related Questions