0

I am trying to create an XML string but the expected output is different from this code

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("Employee");
xml.AppendChild(root);

for (int i = 1; i < datacount; i++)
{
    XmlElement child = xml.CreateElement("EmployeeName");
    child.SetAttribute("value", "Name1");
    root.AppendChild(child);
}

string xmlString = xml.OuterXml;

Expected output:

<?xml version="1.0" encoding="utf-8" ?>
<Employee> 
    <EmployeeName>Name1</EmployeeName>
    <EmployeeName>Name2</EmployeeName>
</Employee>

Current output:

<?xml version="1.0" encoding="utf-8" ?>
<Employee>
    <EmployeeName Value = "Name1" />     
    <EmployeeName Value = "Name1" />       
</Employee>
1
  • 1
    child.InnerText = "Name1"; Commented Feb 18, 2021 at 22:55

1 Answer 1

1
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("Employee");
xml.AppendChild(root);

//Create a new node and add it to the document.
//The text node is the content of the price element.
for (int i = 1; i < datacount; i++)
{
    XmlElement elem = xml.CreateElement("EmployeeName");
    XmlText text = xml.CreateTextNode("Name");
    xml.DocumentElement.AppendChild(elem);
    xml.DocumentElement.LastChild.AppendChild(text);
}
                
string xmlString = xml.OuterXml;

or you can use

child.InnerText="Name1";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.