0

I have to write information from textboxes to XML file on click event. My sample code would look lik this.

XDocument xmlDoc = XDocument.Load(fileName);

        xmlDoc.Element("Mediaplans").Add(new XElement("MediaPlan", new XElement("Media",TxtMedia.Text),
        new XElement("Adtype", TxtAdtype.Text), new XElement("EmailId",TxtEmailId.Text)));

        xmlDoc.Save(fileName).

What I want to know is how do we add attributes to elements with the above method? I am new to this field. any help appreciated.

Thanks, Kruthika

2 Answers 2

1

You can call Add and pass an XAttribute too.

Sign up to request clarification or add additional context in comments.

Comments

0

You can just use add new XAttribute like you have done with XElement.

Have a look at this link for an example

I believe that you should be able to do something like

XDocument xmlDoc = XDocument.Load(fileName);

xmlDoc.Element("Mediaplans").Add(new XAttribute("File name", fileName),new XElement("MediaPlan", new XElement("Media",TxtMedia.Text), new XElement("Adtype", TxtAdtype.Text), new XElement("EmailId",TxtEmailId.Text));

xmlDoc.Save(fileName).

Sorry dont have access to VS at the moment so I cant verify the code.

2 Comments

Thank you for your reply. what I was looking for is dynamically add nodes when a click event occurs. The example seems to be about adding nodes statically, By using element.Add, I am only being able to add a new Xelement, If I have a XAttribute ot be added to one of the Xelements, what is the syntax for using it?
See my updated reply. Let me know if it doesnt work and I will try and verify it.

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.