Appending an existing XML file with XmlWriter - c#

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!

Related

Writing Xml in Windows Phone Application

I have this code that work fine to create an xml document for my WPF application.
var doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
var parentNode = doc.CreateElement("manga");
doc.AppendChild(parentNode);
foreach (var mList in mangaList)
{
var itemNode = doc.CreateElement("item");
var itemAttribute = doc.CreateAttribute("value");
itemAttribute.Value = mList.Key;
itemNode.InnerText = mList.Value;
itemNode.Attributes.Append(itemAttribute);
parentNode.AppendChild(itemNode);
}
var writer = new XmlTextWriter(#"Data\mangalist.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
writer.Close();
Now I want to create similar application for Windows Phone 7.5 and i'm stuck in porting above code to be able to run in WP. After quick searching i found that XmlDocument is not available in Windows Phone and have to switch using XDocument. I am far from familiar with XDocument and hope somebody can help to me make my windows phone apps outputting the same xml.
Thanks
Solution :
After good hints from #Pradeep Kesharwani and #dav_i I managed to port those codes above to use XDocument and StreamWriter instead of XmlDocument and XmlTextWriter which are not available for WP:
var doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
var root = new XElement("manga");
var mangaList = new Dictionary<string, string>();
mangaList.Add("conan", "conan");
mangaList.Add("naruto", "naruto");
foreach (var mList in mangaList)
{
var itemNode = new XElement("item");
var itemAttribute = new XAttribute("value", mList.Key);
itemNode.Value = mList.Value;
itemNode.Add(itemAttribute);
root.Add(itemNode);
}
doc.Add(root);
using (var writer = new StreamWriter(#"Data\mangalist2.xml"))
{
writer.Write(doc.ToString());
}
As I said in comments, XDocument is pretty straight forward -
new XDocument(
new XDeclaration("1.0", "utf-8", "no"),
new XElement("root",
new XElement("something",
new XAttribute("attribute", "asdf"),
new XElement("value", 1234),
new XElement("value2", 4567)
),
new XElement("something",
new XAttribute("attribute", "asdf"),
new XElement("value", 1234),
new XElement("value2", 4567)
)
)
)
Gives the following
<root>
<something attribute="asdf">
<value>1234</value>
<value2>4567</value2>
</something>
<something attribute="asdf">
<value>1234</value>
<value2>4567</value2>
</something>
</root>
Hopefully this will help you!
To automatically populate in a loop, you could do something like this:
var somethings = new List<XElement>();
for (int i = 0; i < 3; i++)
somethings.Add(new XElement("something", new XAttribute("attribute", i + 1)));
var document = new XDocument(
new XElement("root",
somethings));
Which results in
<root>
<something attribute="1" />
<something attribute="2" />
<something attribute="3" />
</root>
This Create method could be used to create a xml doc in wp7
private void CreateXml()
{
string xmlStr = "<RootNode></RootNode>";
XDocument document = XDocument.Parse(xmlStr);
XElement ex = new XElement(new XElement("FirstNOde"));
XElement ex1 = new XElement(new XElement("second"));
ex1.Value = "fdfgf";
ex.Add(ex1);
document.Root.Add(new XElement("ChildNode", "World!"));
document.Root.Add(new XElement("ChildNode", "World!"));
document.Root.Add(ex);
string newXmlStr = document.ToString();
}
This will be the created xml
<RootNode>
<ChildNode>World!</ChildNode>
<ChildNode>World!</ChildNode>
<FirstNOde>
<second>fdfgf</second>
</FirstNOde>
</RootNode>
public void ReadXml()
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Your xml file name", FileMode.Open);
using (XmlReader reader = XmlReader.Create(isoFileStream))
{
XDocument xml = XDocument.Load(reader);
XElement root1 = xml.Root;
}
}

Creating XMLDocument throguh code in asp.net

am trying to generate an XML document like this through code.
<TestRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:2292/RMSchema.xsd">
<Version>3</Version>
<ApplicationHeader>
<AppLanguage />
<UserId>rmservice</UserId>
</ApplicationHeader>
<CustomerData>
<ExistingCustomerData>
<MTN>2084127182</MTN>
</ExistingCustomerData>
</CustomerData>
</TestRequest>
I tried some samples. But they create xmlns for the children, which i dont need. Any help is really appreciated.
I have tried the below code. But it is adding only xmlns to all children, which i dont need
XmlDocument xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
XmlElement xRoot = xDocument.CreateElement("TestRequest", "XNamespace.Xmlns=http://www.w3.org/2001/XMLSchema-instance" + " xsi:noNamespaceSchemaLocation=" + "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = 1;
Thanks
Tutu
I have tried with
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
XmlElement xRoot = xDocument.CreateElement("xsi","RMRequest",xsi);
xRoot.SetAttribute("noNamespaceSchemaLocation", xsi, "http://localhost:2292/RMSchema.xsd");
xDocument.AppendChild(xRoot);
Now the response is
<?xml version=\"1.0\" encoding=\"windows-1252\"?><xsi:TestRequest xsi:noNamespaceSchemaLocation=\"http://localhost:2292/RMSchema.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
Here is the awesome LINQ to XML. Enjoy!
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument doc = new XDocument(new XDeclaration("1.0", "windows-1252", null),
new XElement("TestRequest",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(xsi + "noNamespaceSchemaLocation", "http://localhost:2292/RMSchema.xsd"),
new XElement("Version",
new XText("3")
),
new XElement("ApplicationHeader",
new XElement("AppLanguage"),
new XElement("UserId",
new XText("rmservice")
)
),
new XElement("CustomerData",
new XElement("ExistingCustomerData",
new XElement("MTN",
new XText("2084127182")
)
)
)
)
);
doc.Save(filePath);
If you really want the old API, here it is:
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
var attr = xDocument.CreateAttribute("xsi", "noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
EDIT: From your comments, it looks like you want the xmlns:xsi and other attribute in that specific order. If so, you may have to trick the XmlDocument to add the xmlns:xsi attribute first.
var xDocument = new XmlDocument();
xDocument.AppendChild(xDocument.CreateXmlDeclaration("1.0", "windows-1252", null));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xRoot = xDocument.CreateElement("TestRequest");
// add namespace decl are attribute
var attr = xDocument.CreateAttribute("xmlns:xsi");
attr.Value = xsi;
xRoot.Attributes.Append(attr);
// no need to specify prefix, XmlDocument will figure it now
attr = xDocument.CreateAttribute("noNamespaceSchemaLocation", xsi);
attr.Value = "http://localhost:2292/RMSchema.xsd";
xRoot.Attributes.Append(attr);
xRoot.AppendChild(xDocument.CreateElement("Version")).InnerText = "1";
// .. your other elemets ...
xDocument.AppendChild(xRoot);
xDocument.Save(filePath);
Are you looking for something like this:-
XmlDocument xmldoc = new XmlDocument();
XmlNode root = xmldoc.AppendChild(xmldoc.CreateElement("Root"));
XmlNode child = root.AppendChild(xmldoc.CreateElement("Child"));
XmlAttribute childAtt =child.Attributes.Append(xmldoc.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "My node Innertext";
xmldoc.Save("ABC.xml");

XML Writer stored results to string [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Alternative ways to convert data table to customized XML
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32")));
fillRows("hello1", dt, "product1", 1111);
fillRows("hello2", dt, "product2", 2222);
fillRows("hello3", dt, "product3", 3333);
fillRows("hello4", dt, "product4", 4444);
var xmlColumnZero = dt.AsEnumerable().Select(col => col[0].ToString()).ToArray() ; // row 0 turnovermultiplieer
var xmlRowZero = dt.Columns;
string firstColumnHeader = dt.Columns[0].ToString();
// XmlDocument xmldoc = new XmlDocument();
XmlWriter writer = XmlWriter.Create("employees.xml");
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
// XmlElement first = xmldoc.CreateElement("Order");
//xmldoc.AppendChild(first);
foreach (DataColumn dc in dt.Columns )
{
if (dc.ToString() == firstColumnHeader) continue;
string firstcol = dc.ToString();
writer.WriteStartElement(firstcol);
// XmlElement colRoot = xmldoc.CreateElement(firstcol);
//first.AppendChild(colRoot);
for (int i = 0 ; i <dt.Rows.Count && i< xmlColumnZero.Length ; i++)
{
string firstrow = xmlColumnZero[i];
string dtagaga = dt.Rows[i][dc].ToString();
writer.WriteElementString(firstrow, dtagaga);
// XmlElement rowRoot = xmldoc.CreateElement(firstrow, dtagaga);
//colRoot.AppendChild(rowRoot);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
I want the XMl to be stored into a string while i am creating XMLWriter.
Is there another way i can create xml out of the table
XML should look like
The xml writer method stores everything into an xml file in the program location. Would prefer a string to be saved
<Employees>
<Product_Name>
<hello1>product1</hello1>
hello2>product2</hello2>
hello3>product3</hello3>
hello4>product4</hello4>
</product_name>
<product_Price>
<hello1>1111</hello1>
hello2>2222</hello2>
hello3>3333</hello3>
hello4>4444</hello4>
</product_Price>
</Employees>
Just use overloaded method XmlWriter.Create(StringBuilder output) to create xml string. In this case all output will be written to StringBuilder instead of file:
StringBuilder builder = new StringBuilder();
XmlWriter writer = XmlWriter.Create(builder);
//... build xml here
string xml = builder.ToString();
Also you can write xml to MemoryStream with XmlWriter.Create(Stream output).
Stream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
// ... build xml here
stream.Position = 0;
string xml = new StreamReader(stream).ReadToEnd();
UPDATE
Extension method below will generate your xml string. By default it uses first column as element names, but you can pass any column index for column with meta data. Also I use table name to generate "Employees" tag, so provide name when you create data table DataTable dt = new DataTable("Employees");.
public static string ToXml(this DataTable table, int metaIndex = 0)
{
XDocument xdoc = new XDocument(
new XElement(table.TableName,
from column in table.Columns.Cast<DataColumn>()
where column != table.Columns[metaIndex]
select new XElement(column.ColumnName,
from row in table.AsEnumerable()
select new XElement(row.Field<string>(metaIndex), row[column])
)
)
);
return xdoc.ToString();
}
Usage is very simple:
string xml = dt.ToXml();
Output:
<Employees>
<Product_Name>
<hello1>product1</hello1>
<hello2>product2</hello2>
<hello3>product3</hello3>
<hello4>product4</hello4>
</Product_Name>
<product_Price>
<hello1>111</hello1>
<hello2>222</hello2>
<hello3>333</hello3>
<hello4>444</hello4>
</product_Price>
</Employees>
Use a StringBuilder and create the XmlWriter using the StringBuilder instead of a file:
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
writer.WriteStartDocument();
//...
writer.WriteEndDocument();
var myXmlString = sb.ToString(); //myXmlString will contain the XML
Instead of creating a file
XmlWriter writer = XmlWriter.Create("employees.xml");
You can use String stream
StringWriter sw = new StringWriter();
XmlWriter writer = XmlWriter.Create(sw);
...
...
// sw.ToString(); // string output

How to insert xml data into existing xml in c#?

i added xml file in my windows application, i want to add values to that from textbox..
i used the following code,
string path = "codedata.xml";
XmlDocument doc = new XmlDocument();
if (!System.IO.File.Exists(path))
{
//Create neccessary nodes
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is an XML Generated File");
doc.AppendChild(declaration);
doc.AppendChild(comment);
}
else //If there is already a file
{
// //Load the XML File
doc.Load(path);
}
//Get the root element
XmlElement root = doc.DocumentElement;
XmlElement Subroot = doc.CreateElement("data");
XmlElement Companycode = doc.CreateElement("Companycode");
XmlElement Productcode = doc.CreateElement("Productcode");
XmlElement Productname = doc.CreateElement("Productname");
XmlElement Brandcode = doc.CreateElement("Brandcode");
XmlElement Brandname = doc.CreateElement("Brandname");
Companycode.InnerText = txt_companycode.Text;
Productcode.InnerText = txt_productcode.Text;
Productname.InnerText = txt_productname.Text;
Brandcode.InnerText = txt_brandcode.Text;
Brandname.InnerText = txt_brandname.Text;
Subroot.AppendChild(Companycode);
Subroot.AppendChild(Productcode);
Subroot.AppendChild(Productname);
Subroot.AppendChild(Brandcode);
Subroot.AppendChild(Brandname);
root.AppendChild(Subroot);
doc.AppendChild(root);
//Save the document
doc.Save(path);
//Show confirmation message
MessageBox.Show("Details added Successfully");
it showing error near root.AppendChild(Subroot); can any one help me, wer i made mistake.
You can use Linq to XML, here is an example :
var xDoc = XElement.Load("FilePath");
if (xDoc == null)
return;
var myNewElement = new XElement("ElementName"
new XAttribute("AttributeName", value1),
new XAttribute("AttributeName", value2)
//And so on ...
);
xDoc.Add(myNewElement);
xDoc.Save("FilePath");
The root is null. Try to add Root element when you create XML file.
if (!System.IO.File.Exists(path))
{
//Create neccessary nodes
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is an XML Generated File");
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(doc.CreateElement("Root"));
}
Or use LINQ-XML
string _file=#"c:\sample.xml";
XDocument doc;
if (!File.Exists(_file))
{
doc = new XDocument();
doc.Add(new XElement("Root"));
}
else
{
doc = XDocument.Load(_file);
}
doc.Root.Add(
new XElement("data",
new XElement("CompanyCode","C101"),
new XElement("ProductCode","P101")
)
);
doc.Save(_file);
In null XML DocumentElement is null. Try add Subroot to Document:
XmlElement root = doc.DocumentElement;
root.AppendChild(Subroot);
doc.AppendChild(root);
// new code
doc.AppendChild(Subroot);

writing to xml attributes

Hey all i have code to write to an xml doc from asp
string filePath = Server.MapPath("../XML/MyXmlDoc.xml");
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filePath);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
string startElement = "markings";
xmlWriter.WriteStartElement(startElement);
xmlWriter.Close();
xmlDoc.Load(filePath);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement mainNode = xmlDoc.CreateElement("mark");
XmlElement childNode1 = xmlDoc.CreateElement("studentFirstName");
XmlElement childNode2 = xmlDoc.CreateElement("studentLastName");
XmlElement childNode3 = xmlDoc.CreateElement("className");
XmlElement childNode4 = xmlDoc.CreateElement("marks");
XmlText childTextNode1 = xmlDoc.CreateTextNode("");
XmlText childTextNode2 = xmlDoc.CreateTextNode("");
XmlText childTextNode3 = xmlDoc.CreateTextNode("");
XmlText childTextNode4 = xmlDoc.CreateTextNode("");
root.AppendChild(mainNode);
//this portion can be added to a foreach loop if you need to add multiple records
childTextNode1.Value = "John";
childTextNode2.Value = "Doe";
childTextNode3.Value = "Biology";
childTextNode4.Value = "99%";
mainNode.AppendChild(childNode1);
childNode1.AppendChild(childTextNode1);
mainNode.AppendChild(childNode2);
childNode2.AppendChild(childTextNode2);
mainNode.AppendChild(childNode3);
childNode3.AppendChild(childTextNode3);
mainNode.AppendChild(childNode4);
childNode4.AppendChild(childTextNode4);
//end of loop section
xmlDoc.Save(filePath);
which works fine but i want to store the xml in the following structure
graph
set name="John Doe" value="99";
/graph
instead of
name John Doe /name
value 99 /value
is there a way to store the xml like this? thanks all
You can add an attribute to your XmlElement by using the following syntax (C#) :
XmlAttribute value = xmlDoc.CreateAttribute("value");
childNode1.attributes.appendChild(value);
Hope this helps !
This code will do what you're looking for:
XmlElement graph = xmlDoc.CreateElement("graph");
XmlAttribute name = xmlDoc.CreateAttribute("name");
name.Value = "John Doe";
XmlAttribute value = xmlDoc.CreateAttribute("value");
value.Value = "99";
graph.SetAttributeNode(name);
graph.SetAttributeNode(value);
mainNode.AppendChild(graph);

Categories

Resources