Search code examples
c#xmlxmldocument

New XML document with Key / Value pairs


I am fairly new to programing and I want to create a new key value pair document via xml to send to a web service

<BuildAddOns>
    <UserInput Question="foo" Answer="blahh" Type="String" />
    <UserInput Question="foo" Answer="blahh" Type="String" />
</BuildAddOns>

Solution

  • You can use XDocument to read/write a xml file. Here is the code:

    XElement root = new XElement("BuildAddOns");
    
    XDocument doc = new XDocument(root);
    
    
    XElement element1 = new XElement("UserInput");
    element1.SetAttributeValue("Question", "foo");
    element1.SetAttributeValue("Answer", "blahh");
    element1.SetAttributeValue("Type", "String");
    
    doc.Root.Add(element1);
    
    XElement element2 = new XElement("UserInput");
    element2.SetAttributeValue("Question", "foo");
    element2.SetAttributeValue("Answer", "blahh");
    element2.SetAttributeValue("Type", "String");
    
    doc.Root.Add(element2);
    
    doc.Save(@"C:\New Text Document.txt");