1

我正在尝试以编程方式写入 xml。

试图实现这样的目标:-

<module>
  <moduleCode>EIGA501</moduleCode>
  <moduleTitle>Introduction to 3D Graphics</moduleTitle>
  <credits>15</credits>
  <semester>1</semester>
  <assessmentDetails>
    <assessment>
      <assessmentName>Coursework1</assessmentName>
      <assessmentType>Coursework</assessmentType>
      <assessmentWeighting>25</assessmentWeighting>
    </assessment>
    <assessment>
      <assessmentName>Coursework2</assessmentName>
      <assessmentType>Coursework</assessmentType>
      <assessmentWeighting>35</assessmentWeighting>
    </assessment>
    <assessment>
      <assessmentName>Exam</assessmentName>
      <assessmentType>Exam</assessmentType>
      <assessmentWeighting>40</assessmentWeighting>
    </assessment>
  </assessmentDetails>
  <school>ECS</school>
</module>

请注意,assesmentDetails 节点的格式非常精美,而我正在实现这一点:

<module>
  <moduleCode>someCode</moduleCode>
  <moduleTitle>someCourseTitle</moduleTitle>
  <credits>someCredits</credits>
  <semester>2</semester>
  <assesmentDetails>
    <assesment>
    </assesment>
    <assesment>
    </assesment>
    <assesment>
      <assesmentName>AssesmentName1AssesmentName2</assesmentName>
      <assesmentType>AssesmentType1AssesmentType2</assesmentType>
      <assesmentWeighting>12</assesmentWeighting>
    </assesment>
  </assesmentDetails>
  <school>ECS</school>
</module>

如您所见,我成功地构建了 xml 的其余部分,我正在使用 for 循环尝试“动态地”构建评估部分。如图所示:

for (int i = 0; i < textboxComputer.Count; i++)
            {
                XmlElement newAssesment = document.CreateElement("assesment");
                newAssesmentD.AppendChild(newAssesment);

                TextBox tb1 = (TextBox)textboxComputer[i];
                TextBox tb2 = (TextBox)textboxP[i];
                TextBox tb3 = (TextBox)textboxPercent[i];

                XmlText assesmentN = document.CreateTextNode(tb1.Text);
                XmlText assesmentT = document.CreateTextNode(tb2.Text);
                XmlText assesmentW = document.CreateTextNode(tb3.Text);

                newAssesment.AppendChild(newAssesmentN);
                newAssesment.AppendChild(newAssesmentT);
                newAssesment.AppendChild(newAssesmentW);

                newAssesmentN.AppendChild(assesmentN);
                newAssesmentT.AppendChild(assesmentT);
                newAssesmentW.AppendChild(assesmentW); 
            }

任何帮助,将不胜感激!

4

1 回答 1

0

如果可以使用 LinqToXml,则可以以这种方式添加节点。

XElement a = new XElement("assesment");
a.Add(new XElement("assesmentName", "name text");

你可以找到这样的assesmentDetails节点,

XElement root = XElement.Load(file);
XElement module = root.Elements("module")
             .FirstOrDefault(x => x.Element("moduleCode").Value == "code");
if(null != module)
{
    XElement assesmentDetails = module.Element("assesmentDetails");
    assesmentDetails.Add(a); // <-- Add your new assesment
}
于 2012-05-11T07:31:03.330 回答