如何使用C#读取多级xml?

时间:2012-08-23 11:46:26

标签: c# xml

我有几种xml文件,格式如下。

<!--?xml version="1.0" standalone="yes"?-->
<details>
  <Classes>
    <class>5</class>
    <section>A</class>
  </Classes>
  <student>
    <firstname>Avijeet</firstname>
    <lastname>Roy</lastname>
    <roll>01</roll>
  </student>
  <student>
    <firstname>Saurav</firstname>
    <lastname>Das</lastname>
    <roll>02</roll>
  </student>
   <Classes>
    <class>10</class>
    <section>A</class>
  </Classes>
  <student>
    <firstname>Saumitra</firstname>
    <lastname>Bain</lastname>
    <roll>10</roll>
  </student>
  <student>
    <firstname>Tarun</firstname>
    <lastname>Sing</lastname>
    <roll>11</roll>
  </student>
</details>

现在我想要一个像我的asp.net页面

的数据网格
Class   Section fname    lname  roll
5   A   Avijeet  Roy    01
5   A   Saurav   Das    02
10  A   Saumitra Bain   10
10  A   Tarun    Sing   11

我搜索了很多但却找不到类似的东西。我是C#的新人

2 个答案:

答案 0 :(得分:6)

我认为您所拥有的xml格式符合您的要求,应该是这样的:

<details>
 <Classes>
      <Class>
        <class>5</class>
        <section>A</class>
        <student>
         <firstname>Avijeet</firstname>
         <lastname>Roy</lastname>
         <roll>01</roll>
       </student>
       <student>
        <firstname>Saurav</firstname>
        <lastname>Das</lastname>
        <roll>02</roll>
      </student>
      </Class>

       <Class>
        <class>10</class>
        <section>A</class>
        <student>
         <firstname>Saumitra</firstname>
         <lastname>Bain</lastname>
         <roll>10</roll>
       </student>
       <student>
        <firstname>Tarun</firstname>
        <lastname>Sing</lastname>
        <roll>11</roll>
      </student>
      </Class>
  </Classes> 
</details>

在此之后,您可以使用LINQ to XML:

例如:

XDocument doc = XDocument.Load(xmlPath);
IEnumerable<XElement> selectors = from elements in doc.Elements("details").Elements("Classes").Elements("Class")
                                  select elements;

答案 1 :(得分:0)

您可以尝试创建反映XML文件结构的类型化数据集,并从XML文件加载数据。然后你可以做数据绑定。此外,您可以使用Linq to XML