Reputation: 69
I am trying to create an XML document.
I need the document to display ike this...
<HART:HART xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:HART="www.myurlhere.com" xsi:schemaLocation="www.myurlhere">
This is the code i am using
public FileStreamResult Submission(Models.Reporting.SubmissionViewModel svm)
{
MemoryStream ms = new MemoryStream();
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
XNamespace xmlns = XNamespace.Get("http://www.myurlhere.com");
XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace schemaLocation = XNamespace.Get("http://www.myurlhere.com");
using (XmlWriter xw = XmlWriter.Create(ms, xws))
{
XDocument doc = new XDocument(
new XElement(xmlns + "HART",
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", schemaLocation)
));
doc.WriteTo(xw);
}
ms.Position = 0;
return File(ms, "text/xml", "Sample.xml");
}
However it displays like this
<HART xmlns="http://www.myurlhere.com" xsi:schemaLocation="http://www.myurlhere.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
As you can see the first part is just HART not HART:HART
I have never done this before so any guidance or help would be appreciated.
Thanks
Upvotes: 0
Views: 110
Reputation: 495
the part before the : is just a placeholder to shorten the namespace. This is mostly used as you need to use more than one namespace.
by specifying the namespace on the element level als xmlns= all the childs below will have this namespace until you specify again a child with a xmlns=
if you insist on having <HART:HART xmlns:HART="">
you can do this
new XElement(xmlns + "HART", new XAttribute(XNamespace.Xmlns + "HART", xmlns) ));
Upvotes: 3