Reputation: 43
I'm new to Xdocument and I need your help to understand what I'm doing wrong.
I have the following code:
static void Main(string[] args)
{
XNamespace ns = "http://somesite.com";
XNamespace schemalocation = "http://somesite/schema.xsd";
XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace Xmlns = "http://www.w3.org/2001/XMLSchema-instance";
var date = DateTime.Now;
var guid = "urn:uuid:" + Guid.NewGuid();
XDocument doc = new XDocument(
new XElement(ns + "Message",
new XAttribute("id", guid),
new XAttribute("messageType", Properties.Settings.Default.messageType),
new XAttribute("dateTime", date),
new XAttribute("origin", Properties.Settings.Default.origin),
new XAttribute("originType", Properties.Settings.Default.originType),
new XAttribute("destination", Properties.Settings.Default.destination),
new XAttribute("userName", Properties.Settings.Default.userName),
new XAttribute("xmlns", ns.NamespaceName),
new XAttribute(XNamespace.Xmlns + "xsi", Xmlns),
new XAttribute(xsi + "schemaLocation", schemalocation),
new XElement ("Query",
new XElement("WhereClause", Properties.Settings.Default.WhereClause),
new XElement("ReturnStructure", Properties.Settings.Default.ReturnStructure)
)));
When I save the xml I'm getting an empty xmlns for child element "Query"
<Query xmlns="">
What changes do I need to do on my code to get "Query" without the namespace so it would look like this:
<?xml version="1.0" encoding="utf-8"?>
<Message id="urn:uuid:4ed742cf-1ee4-4548-9105-c230933cf473" messageType="Type" dateTime="datetime" origin="service" originType="type" destination="destination" userName="username" xmlns="http://somesite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://somesite/schema.xsd">
<Query>
<WhereClause>somequery</WhereClause>
<ReturnStructure>somereturn</ReturnStructure>
</Query>
</Message>
Thank for your help
Rafael
Upvotes: 4
Views: 3429
Reputation: 172
You need to add the parent Namespace to Query tag and to the children of Query tag
new XElement (ns + "Query")
new XElement (ns + "WhereClause")
new XElement (ns + "ReturnStructure")
Because once you add namespace to Query the child tags will be left without a namespace and they will show up with empty namespace tags.
Upvotes: 1