7

I have the following code to write some data in an xml file. It works well but the attributes. I can not create attributes and its value for an element.

//.xml file===========================
<?xml version="1.0" encoding="utf-8"?>
<Errors>
   <Error Name="abc" ContactNo="123">
     <Description>Test</Description>
  </Error>
</Errors>

// c# code ===========================
XmlDocument xmlErrors = new XmlDocument();
xmlErrors.Load(Path.Combine(Application.StartupPath, "Errors.xml"));
XmlElement subRoot = xmlErrors.CreateElement("Error");
// subRoot.Attributes[0].Value = "Test 1";
// subRoot.Attributes[1].Value = "Test 2";
XmlElement Description = xmlErrors.CreateElement("Description");
Description.InnerText = currentData.ExamineeName;
subRoot.AppendChild(Description);
xmlErrors.DocumentElement.AppendChild(subRoot);
xmlErrors.Save(Path.Combine(Application.StartupPath, "Errors.xml"));

Would you please help me how to create an attribute and its value? Thanks.

4 Answers 4

9
XmlElement error = Errors.CreateElement("Error");
XmlAttribute errName= Errors.CreateAttribute("Name");
errName.value="abc"
error.Attributes.Append(errName);
Sign up to request clarification or add additional context in comments.

Comments

6

Use SetAttributeValue on a XElement object:

subRoot.SetAttributeValue("Name","Test 1");
subRoot.SetAttributeValue("ContactNo","Test 1");

1 Comment

There is no method SetAttributeValue, but SetAttribute. Anyway, thank you for giving the clue. You deserve upvote.
1

In LINQ2XML

XElement doc=new XElement("Errors",
      new XElement("Error",new XAttribute("Name","abc"),new XAttribute("ContactNo","123")),
      new XElement("Description","Test")
);
doc.Save(path);

Comments

1

the simplest way is to use the following code:

error.SetAttribute("id", "value");

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.