How to create root node with xmlns:xsi but no prefix? - c#

What's the proper way to create a root node without the prefix, but have it display xmlns:xsi="blah"? Basically I want something like this:
<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd" version="0.95">
<Whatever>
</Whatever>
</EDSCrate>
However, I've tried many ways, it just won't give me a simple node without the namespace, and even if it does, it doesn't give me the proper xmlns:xsi in the attribute.
I'd like to avoid any hack like overriding the ToString and replacing the text myself in the XmlWriter.
string uri = "http://www.w3.org/2001/XMLSchema-instance";
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("xsi", uri);
XmlElement root = doc.CreateElement("EDSCrate", uri);
// at this point, it already added xmlns="http://www.w3.org/2001/XMLSchema-instance" without me doing anything
root.RemoveAllAttributes();
// but i want xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"!!
root.SetAttribute("xmlns:xsi", uri);
root.SetAttribute("xsi:noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd");

string uri = "http://www.w3.org/2001/XMLSchema-instance";
var doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
var root = doc.CreateElement("EDSCrate");
doc.AppendChild(root);
root.AppendChild(doc.CreateElement("Whatever"));
var attr = doc.CreateAttribute("xsi", "noNamespaceSchemaLocation", uri);
attr.InnerText = "EDS_Crate_2010-02-10.xsd";
root.SetAttributeNode(attr);
root.SetAttribute("version", "0.95");

I find using Linq2Xml easier.
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xdoc = new XDocument(
new XElement(
"EDSCrate",
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd"),
new XAttribute("version", "0.95"),
new XElement("Whatever","")
)
);
var xml = xdoc.ToString();
OUTPUT:
<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd"
version="0.95">
<Whatever></Whatever>
</EDSCrate>

Related

Convert XMLDocument to XDocument ,getting names spaces Modifing from xsi to p1

i create an XMLDocument:
`
XmlDocument doc = new XmlDocument();
XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
// -----------------------create root-----------------------------
XmlElement rootnode = doc.CreateElement( "BMECAT");
doc.InsertBefore(declaire, doc.DocumentElement);
doc.AppendChild(rootnode);
//Console.WriteLine(sb.ToString());
//get attribute for BmeCat
rootnode.SetAttribute("version", "2005");
XmlAttribute atr = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
atr.Value = "http://www.adlnet.org/xsd/adlcp_v1p3";
rootnode.SetAttributeNode(atr);
rootnode.Attributes.Append(atr);`
then i convert it to XDocument using the function below but i get a NameSpace changed like this
XDocument ToXDocument(XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
`
below the xml and the XDocument
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" p1:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">
<?xml version="1.0" encoding="utf-8"?>
<BMECAT version="2005" xsi:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
You need to explicitly add the xsi namespace declaration manually at the beginning of your element.
Nodes are processed in document order and the namespace declaration appears later after it is first used. It doesn't know to use xsi for the prefix until it's too late.
var doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
var root = (XmlElement)doc.AppendChild(doc.CreateElement("BMECAT"));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
root.SetAttribute("xmlns:xsi", xsi); //set the namespace now
root.SetAttribute("schemaLocation", xsi, "http://www.adlnet.org/xsd/adlcp_v1p3");
root.SetAttribute("version", "2005");

Not getting string in xml formatted form?

I am trying to create a xml document of following format:
<![CDATA[<Caption xmlns="http:happy.x.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.happybus.tv/yy/happybus.xsd">
<TemplateID>xxxxx</TemplateID>
<CaptionOptions>
<CaptionField>
<Field>xxx</Field>
<Text>xxx</Text>
</CaptionField>
<CaptionField>
<Field>xxxx</Field>
<Text>""</Text>
</CaptionField>
</CaptionOptions>
</Caption>]]>
Here is the code that I wrote
XmlDocument xml2 = new XmlDocument();
XmlElement e = xml2.CreateElement("Caption");
e.InnerText ="Hello";
XmlElement template = xml2.CreateElement("TemplateID");
template.InnerText = "#TemplateID";
XmlElement captionOptions = xml2.CreateElement("CaptionOptions");
XmlElement captionField = xml2.CreateElement("CaptionField");
XmlElement fieldId = xml2.CreateElement("FieldID");
fieldId.InnerText = "#FieldID";
XmlElement textstring = xml2.CreateElement("TextString");
textstring.InnerText = "#TextString";
captionField.AppendChild(fieldId);
captionField.AppendChild(textstring);
captionOptions.AppendChild(captionField);
e.AppendChild(template);
e.AppendChild(captionOptions);
xml2.AppendChild(e);
StringWriter string_writer2 = new StringWriter();
XmlTextWriter xml_text_writer2 = new XmlTextWriter(string_writer2);
xml_text_writer2.Formatting = Formatting.Indented;
xml2.WriteTo(xml_text_writer2); // xml is your XmlDocument
string formattedXml2 = string_writer2.ToString();
Console.Write(formattedXml2);
I have tried a similar example with different XML doc but it clearly work, I even tried debugging but it is not getting formatted.
Have you tried using the XDocument and related classes? I find they make manual construction of xml easier and more intuitive since the code looks very similar to the xml. The ToString method seems to output the xml formatted the way you want:
void Main()
{
var xDoc = new XDocument
(
new XElement("Parent",
new XElement("TemplateID", "xxxxx"),
new XElement("CaptionOptions",
new XElement("CaptionField",
new XElement("Field", "xxx"),
new XElement("Text", "xxx")
),
new XElement("CaptionField",
new XElement("Field", "xxxx"),
new XElement("Text", "")
)
)
)
);
Console.WriteLine(xDoc.ToString());
//To enclose the xml in a CDATA, you could use:
var cData = new XCData(xDoc.ToString());
Console.WriteLine(cData.ToString());
}

Inserting xml nodes containing namespaces outside of document node

I'm creating an XML document in C# that is similar to the following
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>2015-05-17-track.kml</name>
</Document>
</kml>
I can create everything except for the kml node. How do I add this to the XmlDocument?
This is the code I'm using, without the kml node.
doc = new XmlDocument();
XmlElement root = doc.CreateElement("Document");
doc.AppendChild(root);
//form the declaration
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null );
doc.InsertBefore(declaration, root);
XmlNode nameNode = doc.CreateNode(XmlNodeType.Element, "name", "");
nameNode.InnerText = name;
root.AppendChild(nameNode);
Append child to DocumentElement.
XmlNode nameNode = doc.CreateNode(XmlNodeType.Element, "name", "");
nameNode.InnerText = name;
doc.DocumentElement.AppendChild(nameNode );
Turns out I was misled by the 'Document' node. It's been a while and I thought the XmlDocument.DocumentElement always had a tag of 'Document'. Wrong!
Here is the revised code
doc = new XmlDocument();
XmlElement root = doc.CreateElement( "kml" );
root.SetAttribute( "xmlns", "http://www.opengis.net/kml/2.2" );
root.SetAttribute( "xmlns:gx", "http://www.google.com/kml/ext/2.2" );
root.SetAttribute( "xmlns:kml", "http://www.opengis.net/kml/2.2" );
root.SetAttribute( "xmlns:atom", "http://www.w3.org/2005/Atom" );
doc.AppendChild( root );
//form the declaration
XmlDeclaration declaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
doc.InsertBefore( declaration, root );
//Document node
XmlElement documentNode = doc.CreateElement( "Document" );
root.AppendChild( documentNode );
//add the name node
XmlNode nameNode = doc.CreateNode( XmlNodeType.Element, "name", "" );
nameNode.InnerText = name;
documentNode.AppendChild( nameNode );

c# write xml muitiable atrrtibutes

I am creating xml file with c#, The xml is:
<?xml version="1.0" encoding="utf-8"?>
<Project Title="old one"
Version="1.5.1.0"
Author=""
EmphasisColor1Label=""
EmphasisColor1="#000000"
EmphasisStyle1="---" >
</Project>
my c# code is:
XmlDocument doc = new XmlDocument();
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(decl);
XmlElement ChatMapper = doc.CreateElement("Project");
doc.AppendChild(ChatMapper);
XmlNode xmldocSelect = doc.SelectSingleNode("Project");
//Crteate Attribute
XmlAttribute attra = doc.CreateAttribute("Title");
attra.Value ="old one";
xmldocSelect.Attributes.Append(attra);
XmlAttribute attrb = doc.CreateAttribute("Version");
attrb.Value ="1.5.1.0";
xmldocSelect.Attributes.Append(attrb);
XmlAttribute attrc = doc.CreateAttribute("EmphasisColor1Label");
attrc.Value ="";
xmldocSelect.Attributes.Append(attrc);
XmlAttribute attrd = doc.CreateAttribute("EmphasisColor1");
attrd.Value ="#000000";
xmldocSelect.Attributes.Append(attrd);
XmlAttribute attre = doc.CreateAttribute("EmphasisStyle1");
attre.Value ="---";
xmldocSelect.Attributes.Append(attre);
That is not smart and too long, anyone knows how to make it shorter?
You can use System.Xml.Linq namespace to create xml. Code snippet in C#:
XDocument doc = new XDocument(
new XElement("Project ",
new XAttribute("Title", "old one"),
new XAttribute("Version", "1.5.1.0"),
new XAttribute("Author", ""),
new XAttribute("EmphasisColor1Label", ""),
new XAttribute("EmphasisColor1", "#000000"),
new XAttribute("EmphasisStyle1", "")
)
);
doc.Save("Project.xml");
Using LINQ:-
using System.Xml.Linq;
var xml =
new XElement("Project",
new XAttribute("Title", "old one"),
new XAttribute("Version", "1.5.1.0"),
new XAttribute("Author", ""),
new XAttribute("EmphasisColor1Label", ""),
new XAttribute("EmphasisColor1", "#000000"),
new XAttribute("EmphasisStyle1", "---")
);
xml.Save("Project.xml");
WITHOUT LINQ:-
XmlDocument doc = new XmlDocument();
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(decl);
XmlElement ChatMapper = doc.CreateElement("Project");
ChatMapper.SetAttribute("Title", "old one");
ChatMapper.SetAttribute("Version", "1.5.1.0");
ChatMapper.SetAttribute("EmphasisColor1", "#000000");
ChatMapper.SetAttribute("EmphasisStyle1", "---");
doc.AppendChild(ChatMapper);
doc.Save("project.xml");

How to create XML in C#

I need to create an XML and return it as a string. Can anyone tell me how to create the following XML using XmlDocument?
<outputs>
<output name="" value="" type=""></output>
<output name="" value="" type=""></output>
<output name="" value="" type=""></output>
</outputs>
UPDATE
var xmlDocument = new XmlDocument();
var xmlNode=xmlDocument.CreateNode(XmlNodeType.XmlDeclaration,"outputs","namespace");
xmlDocument.AppendChild(xmlNode);
var xmlElement = xmlDocument.CreateElement("", "output", "");
xmlDocument.AppendChild(xmlElement);
I think you should consider using XDocument instead of XmlDocument:
var doc = new XDocument(new XElement("outputs",
new XElement("output",
new XAttribute("name", ""),
new XAttribute("value", ""),
new XAttribute("type", "")),
new XElement("output",
new XAttribute("name", ""),
new XAttribute("value", ""),
new XAttribute("type", "")),
new XElement("output",
new XAttribute("name", ""),
new XAttribute("value", ""),
new XAttribute("type", ""))));
You can than easily write the xml into a string:
var myXmlString = doc.ToString();
You can also achieve the same goal with XDocument.Parse() static method:
var doc = XDocument.Parse("<outputs><output></output> (...) </outputs>");
You can add content using loop as well:
var doc = new XDocument(new XElement("outputs"));
var root = doc.Root;
foreach(var o in outputs)
{
root.Add(new XElement("output",
new XAttribute("name", o.Name),
new XAttribute("value", o.Value),
new XAttribute("type", o.Type)));
}
//Create XmlDocument
XmlDocument xmlDoc = new XmlDocument();
//Create the root element
XmlNode outputsElement = xmlDoc.CreateElement("outputs");
//Create the child element
XmlElement Element = xmlDoc.CreateElement("output");
//Create "name" Attribute
XmlAttribute nameAtt = xmlDoc.CreateAttribute("name");
Element.Attributes.Append(nameAtt);
//Create "value" Attribute
XmlAttribute valueAtt = xmlDoc.CreateAttribute("value");
Element.Attributes.Append(valueAtt);
//Create "type" Attribute
XmlAttribute typeAtt = xmlDoc.CreateAttribute("type");
Element.Attributes.Append(typeAtt);
//Append child element into root element
outputsElement.AppendChild(Element);
and to return it as string:
xmlDoc.OuterXml;
string str = "<outputs><output name=\"\" value=\"\" type=\"\"></output><output name=\"\" value=\"\" type=\"\"></output><output name=\"\" value=\"\" type=\"\"></output></outputs>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
And for creating a string again.
string toString = string.Empty;
using (StringWriter stringWriter = new StringWriter())
{
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
doc.WriteTo(xmlTextWriter);
toString = stringWriter.ToString();
}
This will help you a lot, it is a great example about how to Read and Write to an xml file:
http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTutMellli21.aspx
Example code about how to Create elements and a whole XML file, using c# code:
static void Main(string[] args)
{
// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);
// Opens the document
textWriter.WriteStartDocument();
// Write comments
textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
textWriter.WriteComment("myXmlFile.xml in root dir");
// Write first element
textWriter.WriteStartElement("Student");
textWriter.WriteStartElement("r", "RECORD", "urn:record");
// Write next element
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
// Write one more element
textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");
textWriter.WriteEndElement();
// WriteChars
char[] ch = new char[3];
ch[0] = 'a';
ch[1] = 'r';
ch[2] = 'c';
textWriter.WriteStartElement("Char");
textWriter.WriteChars(ch, 0, ch.Length);
textWriter.WriteEndElement();
// Ends the document.
textWriter.WriteEndDocument();
// close writer
textWriter.Close();
}

Categories