在xml中插入并表示文档内的一对多关系

时间:2015-12-01 20:04:39

标签: c# asp.net xml linq

我有xml数据,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<classes>
    <class room_id='1'>
        <classArea></classArea>
        <classFloor></classFloor>
        <maxStudents></maxStudents>
        <teachers>
            <teacher_name></teacher_name>
            <teacher_name></teacher_name>
            <teacher_name></teacher_name>
        </teachers>
    </class>
</classes>

在asp.net c#web app页面中我为room_id,classArea,classFloor,maxStudents创建了文本框以允许用户输入新类,然后我从中创建了XElement来表示xml数据,如下所示:

XElement class = new XElement("class",
                new XAttribute("room_id", IdTb.Text),
                new XElement ("classArea"...
                ...
                ... maxStudents));

为teacher_name强制用户添加文本框,以便每个班级只输入一位教师。

我的问题是如何允许用户同时在teachers元素中输入teacher_name元素的多个值?因为我们有多个价值观,而且我不知道有多少老师可以输入一个...十...或更多。 我应该用什么来解决这个问题,并一次性构建具有完整结构的XElement“class”对象,如按下保存按钮? 请带我解决。

1 个答案:

答案 0 :(得分:1)

不是传递一个XElement教师姓名,而是传递XElements数组。

XElement重载方法之一是

  

public XElement(XName name,params object [] content)

将该数组中的所有对象链接到相同的元素级别。

<强>代码:

// Just populating the teachers names
var teachers = new List<string> { "Sarah", "Rivka", "Lea", "Rachel" };

// You can change the following line to whatever line you want that produces array of XElement in that format.
var teachersXElements = teachers.Select(teacher => new XElement("teacher_name", teacher));

var myClass = new XElement("class",
        new XAttribute("room_id", 1),
        new XElement ("classArea",
            new XElement("teachers", teachersXElements) // Here the "Magic" happens; simple as that.
        )
);

Console.WriteLine(myClass.ToString());

示例输出:

<class room_id="1">
  <classArea>
    <teachers>
      <teacher_name>Sarah</teacher_name>
      <teacher_name>Rivka</teacher_name>
      <teacher_name>Lea</teacher_name>
      <teacher_name>Rachel</teacher_name>
    </teachers>
  </classArea>
</class>