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());
}
Related
this is the code
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("customers");
xml.AppendChild(root);
foreach (var cust in customerlist)
{
XmlElement child = xml.CreateElement("customer");
child.SetAttribute("CustomerId", cust.CustomerId.ToString());
child.SetAttribute("CustomerName", cust.CustomerName);
child.SetAttribute("PhoneNumber", cust.PhoneNumber);
child.SetAttribute("Email", cust.Email);
root.AppendChild(child);
}
string s = xml.OuterXml;
I want my string to have next lines added to it instead of a single xml document
My string is coming as continuous
< x >xxxxx< /x > < x >xxxxx< /x >
You can use the XmlTextWriter class to format the XML as a string like this:
StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;
xml.WriteTo(xml_text_writer); // xml is your XmlDocument
string formattedXml = string_writer.ToString();
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>
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");
I would like to add multiple records to the xml file and here is the code which i am using,
XmlTextWriter xwriter = new XmlTextWriter("C:\\Users\\Desktop\\TestFolder\\Xdoc1.xml", Encoding.UTF8);
xwriter.Formatting = Formatting.Indented;
xwriter.WriteStartElement("Employee");
xwriter.WriteStartElement("Person");
xwriter.WriteStartElement("Name");
xwriter.WriteString(textBox1.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Designation");
xwriter.WriteString(textBox2.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Employee ID");
xwriter.WriteString(textBox3.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Email");
xwriter.WriteString(textBox4.Text);
xwriter.WriteEndElement();
xwriter.WriteEndElement();
xwriter.WriteEndElement();
xwriter.Close();
the problem with this code is that only one record can be added. When i try to add the 2nd record, the previous record is overwritten.
Linq to XML makes xml task easier. Look at below code.
if (!System.IO.File.Exists("D:\\Employees.xml"))
{
XElement element = new XElement("Employees");
element.Save("D:\\Employees.xml");
}
XElement doc = XElement.Load("D:\\Employees.xml");
XElement employee = new XElement("Employees",
new XElement("Employee",
new XElement("Person",
new XElement("Name",
textBox1.Text),
new XElement("Designation",
textBox2.Text),
new XElement("EmployeeID",
textBox3.Text),
new XElement("Email",
textBox4.Text))));
doc.Add(employee);
doc.Save("D:\\Employees.xml");
here is no need to convert xmlWriter class.
string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Candidates.xml");
xmldoc = new XmlDocument();
xmldoc.Load(xmlFile);
root = xmldoc.DocumentElement;
try
{
XmlNode CandidateNode = xmldoc.CreateNode(XmlNodeType.Element, "Candidate", "");
XmlNode id = xmldoc.CreateNode(XmlNodeType.Element, "CandidateId", "");
id.InnerText = "1";
CandidateNode.AppendChild(id);
XmlNode subPositionId = xmldoc.CreateNode(XmlNodeType.Element, "SubPositionId", "");
subPositionId.InnerText = candidate.PositionId.ToString();
CandidateNode.AppendChild(subPositionId);
XmlNode firstName = xmldoc.CreateNode(XmlNodeType.Element, "FirstName", "");
firstName.InnerText = candidate.FirstName;
XmlNode lastName = xmldoc.CreateNode(XmlNodeType.Element, "LastName", "");
lastName.InnerText = candidate.LastName;
CandidateNode.AppendChild(firstName);
CandidateNode.AppendChild(lastName);
root.AppendChild(CandidateNode);
xmldoc.Save(xmlFile);
This will help you.
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();
}