在 c# 中创建 XML 属性

本文关键字:XML 属性 创建 | 更新日期: 2023-09-27 18:32:37

我有以下代码在xml文件中写入一些数据。它工作得很好,但属性。我无法为元素创建属性及其值。

//.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"));

你能帮我如何创建一个属性及其值吗?谢谢。

在 c# 中创建 XML 属性

XmlElement error = Errors.CreateElement("Error");
XmlAttribute errName= Errors.CreateAttribute("Name");
errName.value="abc"
error.Attributes.Append(errName);

XElement 对象上使用 SetAttributeValue:

subRoot.SetAttributeValue("Name","Test 1");
subRoot.SetAttributeValue("ContactNo","Test 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);

最简单的方法是使用以下代码:

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