开发者

Adding XML element for before element with different value from previous element group

I have an XML file I am reading in the code-behind C# ASP.Net page which lists staff details and is organised according to the team they belong to. See below:

<user>
<firstname>Tony</firstname>
<surname>Smith</surname>
<team>Board A</team>
</user>
<user>
<firstname>Paula</firstname>
<surname>Ram</surname>
<team>Board A</team>
</user>
<user>
<firstname>Linda</firstname>
<surname>Smith</surname>
<team>Board b</team>
</user>
<user>
<firstname>Sam </firstname>
<surname>Peak</surname>
<team>Board b</team>
</user>

What I would like to do is the following:

<group>Board A</group>
<user>
<firstname>Tony</firstname>
<surname>Smith</surname>
<team>Board A</team>
</user>
<user>
<firstname>Paula</firstname>
<surname>Ram</surname>
<team>Board A</team>
</user>
<user>
<group>Board B</group>
<firstname>Linda</firstname>
<surname>Smith</surname>
<team>Board b</team>
</user>
<user>
<firstname>Sam </firstname>
<surname>Peak&l开发者_C百科t;/surname>
<team>Board b</team>
</user>

So basically insert a new element with the name of the team the the elements that follow it contain in the team element? I'm not sure if I'm malking any sense?

Ta.

Momo


With xml it would be kind of redundant to use the structure of your second example, because you can already group your elements by team with xpath (or LINQ). In XPATH:

"/user[team='Board b']"

if you have System.Xml.XmlNode

string currentGroup = "Board B"; //get this from some control
XmlNodeList groups = xdoc.SelectNodes(String.Format("/user[team='{0}']",currentGroup));

or if you have a System.Xml.XPath.XPathNavigator

string currentGroup = "Board B";
XPathNodeIterator groups = xNav.Select(String.Format("/user[team='{0}']",currentGroup));

Or you can place your "users" in the "group" element:

<group name="Board A">
    <user>
      <firstname>Tony</firstname>
      <surname>Smith</surname>
      <!-- <team>Board A</team> -->
    </user>
    <user>
      <firstname>Paula</firstname>
      <surname>Ram</surname>
    </user>
</group>

And then as an example of how to select them:

string currentGroup = "Board B";
XmlNodeList groups = xdoc.SelectNodes(String.Format("//user[parent::group/@name='{0}']",currentGroup));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜