Reputation: 620
I am trying to get the following xml format using c#
<Content xmlns="uuid:5c2dffe6-cf72-4211-a8a0-dc6a7baf3ff1">
<redirect xmlns:xlink="http://www.w3.org/1999/xlink">
<key>formssss</key>
<value>/AAAAAAA</value>
</redirect>
My initial issue was escaping the xml attribute and I was using the following code when trying to create an xml node
string name = @"Content xmlns=uuid:5c2dffe6-cf72-4211-a8a0-dc6a7baf3ff1";
//build root xml node <redirects> </redirects>
var rootNode = new XElement(name);
It keeps falling over with the following error
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: The ' ' character, hexadecimal value 0x20, cannot be included in a name.
Why when i have escaped the string? i have also tried to use back slashes.
Using the answers provided by John below i was able to compile but the xml output was not including the attribute. This is my output as it stands
<Content>
<Redirect>
<key>/*$0*/</key>
<value>/</value>
</Redirect>
</Content>
As you can see i am missing the attribute namespaces
Can anyone help please?
Upvotes: 0
Views: 307
Reputation: 161801
The parameter to the XElement
constructor is the local name of the element, not name plus namespace.
Try:
XNamespace ns = "uuid:5c2dffe6-cf72-4211-a8a0-dc6a7baf3ff1";
var rootNode = new XElement(ns + "Content");
To get the complete output you're looking for, you should try:
formssss /AAAAAAA
XNamespace ns = "uuid:5c2dffe6-cf72-4211-a8a0-dc6a7baf3ff1";
var rootNode = new XElement(ns + "Content",
new XElement(ns+"redirect",
new XElement(ns+"key", "formssss"),
new XElement(ns+"value", "/AAAAAAA")));
You do not need the "xlink" namespace because you are not referring to it in your XML.
All of these elements are in the same namespace. If this code does not produce an "xmlns" element on the root, then I'm surprised and will look at it later.
Upvotes: 4