Setting XML namespaces with the System.Xml.Linq API

I'm having trouble generating XML along the lines of this:

<Root xmlns:brk="http://somewhere">

This code get me most of the way, but I can't get the 'brk' namespace in front of the nodes;

 var rootNode = new XElement("Root");
 rootNode.Add(new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere"));

 var childNode = new XElement("child1");
 childNode.Add(new XElement("node1",123456));

I've tried this:

XNamespace brk = "http://somewhere";
childNode.Add(new XElement(brk+"node1",123456));

and this

XNamespace brk = "http://somewhere";
childNode.Add(new XElement("brk:node1",123456));

but both cause exceptions.


You are almost there, but you made one simple error in your first code example. I believe this is what you require:

XNamespace brk = "";
XElement root = new XElement("Root",
    new XAttribute(XNamespace.Xmlns + "brk", ""));

XElement childNode = new XElement("child1");
childNode.Add(new XElement(brk + "node1",123456));

The main difference here is where I add node1 to childNode as follows:

childNode.Add(new XElement(brk + "node1",123456));

This code, given an XmlWriter and XDocument gives me the output:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:brk="">

See MSDN for details of using XNamespace.

I believe the problem is that the root element needs to have the namespace as well:

XElement root = new XElement("Root",
    new XAttribute(XNamespace.Xmlns + "brk", ""));

needs to be:

XElement root = new XElement(brk + "Root",
    new XAttribute(XNamespace.Xmlns + "brk", ""));

This is solotuion and working fine.

 using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using System.Xml.Serialization;

    namespace CreateSampleXML
        public partial class Form1 : Form
            public Form1()
                XNamespace xm = "";
                XElement rt= new XElement("Root", new XAttribute(XNamespace.Xmlns + "brk", ""));
                XElement cNode = new XElement("child1");
                cNode.Add(new XElement(xm + "node1", 123456));
                cNode.Add(new XElement(xm + "node2", 500000000));
                XDocument doc2 = new XDocument(rt);

Need Your Help

Submitting app to app store which is not iPhone 5 screen compatible

iphone ios app-store iphone-5

I submitted an app which is not iPhone 5 screen compatible. I got a response from the App Store team as follows:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.