开发者

c# - Linq 2 XML - how to read elements with the same names

the stucture of xml is:

<Rules>
    <rule ID="1" Parameter="IsD">
      <body>
        <ID>2</ID>
        <Ratio>=</Ratio>
        <Value>no</Value>
        <Operation>A开发者_JAVA百科ND</Operation>
        <ID>3</IF_ID>
        <Ratio>=</Ratio>
        <Value>yes</Value>
      </body>
      <value>no problems</value>
    </rule>
</Rules>

How can I read elements and create a rule with the following structure:

If (<ID><Ratio><Value><Operation><ID><Ratio><Value>)

ID is a question ID. In my case:

If (2 == no && 3 == yes)

Please, help me.


You could use the Elements method of the XElement class. For instance (supposing that you loop over all rules) you could write

foreach (var rule in document.Root.Descendants("rule")) {
  var body = rule.Element("body");
  for (var i=0; i<body.Elements("ID").Count) {
    var id = body.Elemets("ID").ElementAt(i);
    var ratio = body.Elements("Ratio").ElementAt(i);
    var value = body.Elements("Value").ElementAt(i);
    /// ...
  }
}

Notet that accessing the elements of the Elements enumeration by use of ElementAt() might not be very efficient, another approach would be to iterate over the different subelements with separate foreach loops and store them in a List (or better, use the ToList Extension method).

The point is, that the Elements enumeration returns the subelements in document order i.e. in the same order as they appear in the input document (which is, what you need here).

A better solution would be (IMO) to put more structure in your input document in order to reflect the logic, like:

<Rules>
  <rule ID="1" Parameter="IsD">
    <body>
      <term >
        <ID>2</ID>
        <Ratio>=</Ratio>
        <Value>no</Value>
      </term>
      <term operation="and">
        <ID>3</IF_ID>
        <Ratio>=</Ratio>
        <Value>yes</Value>
      </term>
  </body>
  <value>no problems</value>
</rule>

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜