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();
}
Related
I've used the following code to create an XML file:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
I need to insert nodes dynamically creating the following structure:
<?xml version="1.0" encoding="utf-8"?>
<School />
<Student>
<FirstName>David</FirstName>
<LastName>Smith</LastName>
</Student>
...
<Teacher>
<FirstName>David</FirstName>
<LastName>Smith</LastName>
</Teacher>
...
</School>
How can I do it? The values of "FirstName" and "LastName" should be read from the keyboard and the values can be entered at any time, of course under existing.
you can use Linq Xml
XDocument doc = XDocument.Load(xmlFilePath);
XElement school = doc.Element("School");
school.Add(new XElement("Student",
new XElement("FirstName", "David"),
new XElement("LastName", "Smith")));
doc.Save(xmlFilePath);
Edit
if you want to add Element to Existing <Student>, just add an Attribute before
school.add(new XElement("Student",
new XAttribute("ID", "ID_Value"),
new XElement("FirstName", "David"),
new XElement("LastName", "Smith")));
Then you can add further Details to the Existing <Student> by search -> get -> add
XElement particularStudent = doc.Element("School").Elements("Student")
.Where(student => student.Attribute("ID").Value == "SearchID")
.FirstOrDefault();
if(particularStudent != null)
particularStudent.Add(new XElement("<NewElementName>","<Value>");
finally I succeeded :)
if (!File.Exists("Test.xml"))
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");
xmlWriter.WriteStartElement("Student");
xmlWriter.WriteElementString("FirstName", firstName);
xmlWriter.WriteElementString("LastName", lastName);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
}
}
else
{
XDocument xDocument = XDocument.Load("Test.xml");
XElement root= xDocument.Element("School");
IEnumerable<XElement> rows = root.Descendants("Student");
XElement firstRow= rows.First();
firstRow.AddBeforeSelf(
new XElement("Student",
new XElement("FirstName", firstName),
new XElement("LastName", lastName)));
xDocument.Save("Test.xml");
}
Let me give you a suggestion. When you creating your xml file, give an unique id to your students like this:
// to store the id variable, if you create more than one student you can increase it
count = 0;
xmlWriter.WriteStartElement("School");
xmlWriter.WriteAttributeString("ID",count.ToString());
xmlWriter.WriteEndElement();
Then when you need to add information to this student you can get ID,Firstname and Lastname and you can edit your XML file with LINQ to XML like this:
int id = Convert.ToInt32(txtStudentId.Text);
XDocument xDoc = XDocument.Load("Test.xml");
XElement student = xDoc.Descendants("Student").Where(x => (string) x.Attribute("ID") == id).FirstOrDefault();
if (student != null)
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
XElement first = new XElement("FirstName", firstName);
XElement last = new XElement("LastName", lastName);
student.Add(first);
student.Add(last);
xDoc.Save("Test.xml");
}
I have a suggestion for the next time:
string nameFile = "Test.xml";
bool newFile = false;
if (!File.Exists(nameFile))
{
newFile = true;
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");
xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
}
else
{
doc = new XmlDocument();
doc.Load(nameFile);
// Create a XPathNavigator
// You can go where you want to add
// In this case it is just after last child of the roor
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToChild("School", "");
xmlWriter = navigator.AppendChild();
}
// From here you can work only with xmlWriter,
// One will point on a file and the other on the stream of xmlDocument
// So you will need to save the document in the second choise
xmlWriter.WriteStartElement("Student");
xmlWriter.WriteElementString("FirstName", firstName);
xmlWriter.WriteElementString("LastName", lastName);
xmlWriter.WriteEndElement();
// End document / close or save.
if (newFile)
xmlWriter.WriteEndDocument();
xmlWriter.Close();
if (!newFile)
doc.Save(nameFile);
It should work. :)
I know you asked for XmlWriter, but I believe you can achieve this using less code with XDocument. Here is my solution:
var filePath = "path/XmlFile.xml";
var xmlDoc = XDocument.Load(filePath);
var parentElement = new XElement("Student");
var firstNameElement = new XElement("FirstName", firstNameVariable);
var lastNameElement = new XElement("LastName", lastNameVariable);
parentElement.Add(firstNameElement);
parentElement.Add(lastNameElement);
var rootElement = xmlDoc.Element("School");
rootElement?.Add(parentElement);
xmlDoc.save();
This is based on the following XML structure and will append at ... :
<School>
<Student>
<FirstName>John</FirstName>
<LastName>Johnson</LastName>
</Student>
...
</School>
Hope this helps!
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());
}
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.