I'm having trouble generating XML along the lines of this:
<Root xmlns:brk="http://somewhere">
<child1>
<brk:node1>123456</brk:node1>
<brk:node2>500000000</brk:node2>
</child1>
</Root>
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));
rootNode.Add(childNode);
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 = "http://somewhere.com";
XElement root = new XElement("Root",
new XAttribute(XNamespace.Xmlns + "brk", "http://somewhere.com"));
XElement childNode = new XElement("child1");
childNode.Add(new XElement(brk + "node1",123456));
root.Add(childNode);
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="http://somewhere.com">
<child1>
<brk:node1>123456</brk:node1>
</child1>
</Root>
See MSDN for details of using XNamespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With